DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • The Airlock Pattern: A Mathematician's Secret to Preventing Cascade Failures
  • How AI-Driven Software Automation Reduced Deployment Failures by 40%?
  • Deployment Strategies for Self-Hosted Open-Source Applications: Balancing Efficiency and Control
  • The "Unified Manifest" Pattern: Automating Blue-Green Deployments on Kubernetes

Trending

  • Implementing Secure API Gateways for Microservices Architecture
  • Jakarta EE 12: Entering the Data Age of Enterprise Java
  • Reactive Ops to Autonomous Infrastructure: How Agentic AI Is Redefining Modern DevOps
  • Why Your RAG Pipeline Will Fail Without an MCP Server
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Deployment
  4. Laravel + Next.js Integration Guide (Real-World Setup, 2025)

Laravel + Next.js Integration Guide (Real-World Setup, 2025)

This guide walks through a production setup where a Laravel 12 backend powers a Next.js 15 frontend with cookie-based auth via Laravel Sanctum.

By 
Jeff Tomas user avatar
Jeff Tomas
·
Nov. 07, 25 · Tutorial
Likes (0)
Comment
Save
Tweet
Share
4.6K Views

Join the DZone community and get the full member experience.

Join For Free

The goal is simple: build a secure app that uses SSR or SSG for SEO, CSRF-safe session cookies, clear CORS rules, and a smooth deploy to Vercel plus Forge or Vapour. 

By the end, readers will know how to wire Laravel routes and controllers, fetch from Next.js with credentials, handle CSRF and sessions, and deploy with confidence. A short troubleshooting list covers common 401, 419, and CORS issues so teams do not get stuck.

Teams will learn:

  • How to structure Laravel endpoints, middleware, and resources
  • How to fetch with credentials in Next.js and handle CSRF
  • How to set CORS and session cookies for both local and production environments
  • How to deploy to Vercel and Forge or Vapour, with a safe rollout plan

What Will Be Built and Why This Laravel + Next.js Setup Works in 2025

This architecture uses clear roles. Laravel 12 handles data, auth, validation, caching, and queues. Next.js 15 handles UI, routing, SEO, and streaming. The backend exposes a REST API. The frontend consumes it using SSR for dynamic pages or SSG and ISR where possible.

  • Stack and versions that play well today: Laravel 12, PHP 8.3 or higher, MySQL 8 or Postgres 14 or higher, Redis for cache and queues, Next.js 15 with the App Router, Node 18 or higher.
  • Why REST plus Sanctum: Simple session cookies, strong CSRF story, easy mental model. It works for SPAs, SSR, and mixed rendering without storing tokens in localStorage.
  • Security model in one line: Session cookies set with SameSite=None and Secure in production, CORS allows the Next.js domain, and the CSRF token comes from the Sanctum endpoint.
  • Local development plan: Laravel at http://localhost:8000 and Next.js at http://localhost:3000. Use HTTPS in production for both.
  • Repos: A two-repo approach gives separate deploys and clear ownership. A monorepo gives shared tooling and atomic PRs. Both work well.

Stack and Versions to Use

  • Laravel 12, PHP 8.3+
  • Next.js 15 with the App Router, Node 18+
  • MySQL 8 or Postgres 14+, Redis for cache and queues
  • Laravel Sanctum for session-based auth
  • Vite for Laravel assets, even if the frontend is separate
  • Docker is optional; it helps with parity across machines and CI

If a team prefers to hold on to Next.js 14 for now, the App Router flow is similar and still a safe choice.

Project Layout and Repos

Two simple layouts work:

  1. Two repos
    • api-laravel
    • web-next
  2. Monorepo
    • apps/laravel-backend
    • apps/next-frontend

Data Flow and Security Model

  • Next.js first requests the Sanctum CSRF cookie from Laravel.
  • Next.js posts credentials to the login endpoint, with credentials included.
  • Laravel sets HTTP-only session cookies on success.
  • Subsequent API calls include credentials so the session stays active.
  • In production, use HTTPS. Cookies must use Secure and SameSite=None for cross-site use.
  • CORS allows only the frontend origin. Credentials must be enabled in both browser requests and Laravel CORS.
  • Apply rate limits to protect auth and read-heavy endpoints.

Local Dev URLs and Ports

  • Laravel: http://localhost:8000
  • Next.js: http://localhost:3000

Add these origins to CORS in Laravel and enable credentials. For local HTTPS, mkcert can help, but HTTP is fine for development if cookies and CSRF are handled with care.

Setting Up Laravel 12 as a Clean REST API With Sanctum

This section covers a practical setup that avoids common footguns. It keeps code mentions light and focuses on what to configure and why.

What will be added:

  • Versioned REST endpoints under /api/v1
  • Sanctum for session-based auth
  • CORS and CSRF tuned for a separate Next.js domain
  • Safe defaults for validation, resources, and pagination
  • Easy performance wins with caching, eager loading, and rate limiting

For more context on SSR and Sanctum, this guide aligns with the core points covered in Integrating Laravel Sanctum with Next.js SSR: Key Points.

Core Installation and Configuration

  • Create a new Laravel 12 project. Set PHP to 8.3 or higher.
  • Require Sanctum, publish config if needed, and run migrations.

Auth Routes and Middleware

Minimum endpoints:

  • GET sanctum/csrf-cookie
  • POST login
  • POST register
  • POST logout
  • GET /api/v1/user or /api/v1/me behind auth:sanctum

All protected routes use the auth: sanctum middleware. The frontend must fetch the CSRF cookie before posting to the login or logout endpoints. This avoids 419 errors.

Controllers, Validation, and API Resources

  • Organize controllers under App\Http\Controllers\API\V1.
  • Use form request classes for validation. Keep rules clear and messages helpful.
  • Standardize responses with Laravel API resources. This makes payloads consistent.
  • Add pagination to list endpoints, with a sensible default page size.
  • Return clear error responses with messages and HTTP status codes that match the problem.

Safety and Speed Defaults

  • Enable rate limiting on auth and write endpoints. Apply sensible user-based or IP-based limits.
  • Add eager loading to eliminate N+1 queries.
  • Cache read-heavy endpoints where possible. Use tags to clear the cache when data changes.
  • Sanitize and validate all input. Return only the needed fields in responses.
  • Plan for API versioning under /api/v1 so future changes do not break clients.

Building the Next.js 15 Frontend That Talks to Laravel

Next.js handles SSR and SSG with the App Router. Server Components fetch data on the server, which keeps secrets safe and reduces client work. Use Route Handlers for server-side API plumbing when helpful.

For a step-by-step walkthrough of pairing these versions, this reference pairs nicely with the flow here: How to Connect Next.js 15 with Laravel 12.

Project Init and Environment

  • Create a new Next.js 15 app with the App Router.
  • Set NEXT_PUBLIC_API_URL for browser-safe reads when needed.
  • Set a private API_URL for server-only usage. Never expose secrets in NEXT_PUBLIC variables.
  • In server code, use process.env when building fetch requests. Avoid leaking internal URLs to the client unless intended.

Data Fetching Model: SSR, SSG, and ISR

  • SSR for user-specific pages or fast-changing data.
  • SSG for content that changes rarely.
  • ISR for content that can cache with regular refresh, like product lists.
  • In the App Router, favour Server Components for most data fetching. This keeps tokens and cookies in the server context.
  • Set revalidate per route to control ISR timings.

Credentials and Cookies in Next.js

  • Use fetch with credentials included so cookies flow both ways.
  • The login sequence is always: get the CSRF cookie from Laravel, then post login with credentials, then fetch protected routes.
  • In Route Handlers, forward cookies from the request to Laravel.
  • In middleware, check for an auth cookie or make a quick user call, then redirect if missing.

UI States, Errors, and DX

  • Show loading states with Suspense and route-level loading.js.
  • Handle exceptions with error.js and boundaries around risky parts.
  • If client fetching is needed, use a small fetch helper or a library like SWR. Keep it simple.
  • Use TypeScript with plain types that match the API resource shapes.
  • Add metadata for title and description. Use the metadata API for per-page SEO touches.

End-to-End Auth With Laravel Sanctum and Next.js

This is the flow used in production. It avoids 401 and 419 surprises and works with SSR.

Login Flow That Just Works

  • Step 1: Next.js calls GET sanctum/csrf-cookie with credentials included.
  • Step 2: Next.js posts to login with email and password, also with credentials.
  • Step 3: Laravel sets the session cookie. Next.js then calls /api/v1/user to fetch the profile.
  • Place this logic in Route Handlers or server actions. Keep it on the server where possible so cookies do not leak.

Protecting Pages and API Calls

  • Use middleware to check for an auth cookie or make a fast probe call to /api/v1/user.
  • If not authenticated, redirect to the login page.
  • On the server, verify auth before rendering user pages.
  • Handle 401 with a redirect or a clear message. Avoid loops by checking the current route.

User State Across the Server and the Client

  • Fetch the current user on the server for the first render. The nav can render with the right state without flashes.
  • Pass only necessary fields to client components. Do not send the entire user or sensitive data to the browser.
  • After login or logout, refresh the user data so the UI updates at once. A simple revalidate or a server action call works well.

Logout and Session Expiration

  • Call POST logout on Laravel to clear the session.
  • After logging out, redirect to a public route, often the home or login page.
  • In production, cookies should use Secure and SameSite=None for cross-site use.
  • Handle session timeouts by refetching user state. If it fails, redirect to login. Keep the UX smooth and predictable.

Deploying With Confidence: Vercel for Next.js, Forge or Vapour for Laravel

A good production rollout prevents most first-deploy bugs. Set the environment variables with care, match domains, and test cookies over HTTPS.

For another practical overview of this pairing and deployment tradeoffs, compare notes with Connecting Laravel 12 with Next.js: A Comprehensive Guide.

Hosting Plan and Environment

  • Laravel can run on a VPS or managed host via Forge, or it can run serverless via Vapour.
  • Use PHP 8.3+, a managed database, and Redis for cache and queues.
  • Next.js deploys to Vercel. Choose SSR or static where it fits.
  • Set environment variables on both platforms. Do not ship secrets in the frontend bundle.

Domains, TLS, CORS, and Cookies

  • Use HTTPS for both apps. No exceptions in production.
  • In Laravel CORS, allow the Next.js domain and enable credentials.
  • Set cookies with Secure and SameSite=None for cross-site sessions.
  • Set the cookie domain to the API domain or the base domain, depending on your topology.
  • APP_URL should match the backend domain. NEXT_PUBLIC_API_URL or API_URL should match the final API domain used by Next.js.

CI/CD and Performance

  • Cache dependencies in CI to speed deploys.
  • Run Laravel migrations during deploy, and warm route, config, and view caches.
  • Use Redis for cache and queues, and tune the eviction policy.
  • In Next.js, add ISR for content that benefits from caching. Keep revalidating values practical.
  • Add monitoring and error reporting on both sides. Ship logs somewhere that the team checks daily.

Troubleshooting Common Issues

  • 401 Unauthorized: usually missing credentials on fetch, wrong cookie domain, or the cookie is not sent due to CORS settings. Confirm credentials: include is set, and the domain matches.
  • 419 Page Expired: CSRF cookie was not set before posting to the login or logout page. Always call sanctum/csrf-cookie first, with credentials.
  • CORS errors: the allowed origin or headers do not match. Credentials might not be enabled on both sides. Fix the origin string, headers, and supports_credentials in Laravel, and include credentials in requests.
  • Mixed content: one app on HTTP and the other on HTTPS. Both must use HTTPS in production.
  • Time skew: if cookies fail in some regions, check the server time and timezone. Large clock drift breaks sessions and CSRF windows.

Conclusion

This setup gives a clean split of concerns, a secure cookie-based auth flow, and fast pages using SSR, SSG, or ISR where needed. The production path stays simple: Vercel for Next.js, Forge or Vapour for Laravel, with managed DB and Redis. The short checklist is easy to keep:

  • Laravel 12 API versioned under /api/v1
  • Sanctum session auth working with CSRF cookies
  • CORS locked to the frontend domain, credentials enabled
  • Next.js 15 fetching with credentials and server-side checks
  • Protected routes in place, both apps live on HTTPS

Next steps: Add API tests, wire API versioning for future changes, add monitoring and alerts, and plan cache and queue strategies as traffic grows. Want to go deeper on SSR and auth nuances? Keep a reference log of 401 and 419 patterns and how they were fixed, then automate those checks in CI.

Laravel Next.js Software deployment

Opinions expressed by DZone contributors are their own.

Related

  • The Airlock Pattern: A Mathematician's Secret to Preventing Cascade Failures
  • How AI-Driven Software Automation Reduced Deployment Failures by 40%?
  • Deployment Strategies for Self-Hosted Open-Source Applications: Balancing Efficiency and Control
  • The "Unified Manifest" Pattern: Automating Blue-Green Deployments on Kubernetes

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook