How to integrate Next.js with Laravel: A practical guide

Updated: January 18, 2024 By: Guest Contributor Post a comment

Introduction

Leveraging the full-stack potential by combining the power of Laravel as the backend and Next.js as the frontend framework is becoming increasingly attractive to developers. This guide covers a step-by-step process for integrating Next.js with Laravel, creating a seamless development experience.

Understanding the Stack

Laravel serves as a robust server-side PHP framework that handles business logic and data management. Next.js, a React framework, provides robust features for server-rendered or static-generated React applications. Integrating these two can yield a high-performance full-stack application.

Prerequisites

  • Basic knowledge of PHP and Laravel
  • Understanding of JavaScript and React
  • Node.js and npm installed
  • Composer for managing PHP dependencies

Project Setup

We begin by setting up a new Laravel project and a Next.js app within a unified project directory.

composer create-project laravel/laravel laravel-nextjs
mkdir laravel-nextjs/frontend
npx create-next-app laravel-nextjs/frontend

This command creates a new Laravel project and a ‘frontend’ directory which will contain the Next.js app.

API Development

Before concerning ourselves with Next.js, we should expose the necessary APIs from Laravel. You can utilise regular Laravel routes or dive into API resources for more complex scenarios. An example API route might look like:

Route::get('/api/users', function () {
    return User::all();
});

Integrating Next.js

Now switch to the Next.js directory and begin setting up the API communication.

cd laravel-nextjs/frontend

The next step is to set up an API client, such as Axios, to interact with the Laravel backend.

npm install axios

Create an API utility file for making requests:

// utils/api.js
import axios from 'axios';

const APIEndpoint = axios.create({
    baseURL: 'http://localhost:8000/api',
});

export const getAllUsers = async () => {
    const response = await APIEndpoint.get('/users');
    return response.data;
};

With Axios configured, you can now call the Laravel API from within your React components.

CORS Configuration

A critical consideration in the integration is cross-origin resource sharing (CORS). Laravel includes a CORS package out-of-the-box, which can be configured as follows:

// In Laravel, edit the 'cors.php' in the 'config' directory
'paths' => ['api/*'],

'allowed_methods' => ['*'],
'allowed_origins' => ['http://localhost:3000'], // Allow the Next.js app
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => false,

These settings ensure that requests from the Next.js frontend are accepted by the Laravel server.

Static Assets Handling

Laravel provides a powerful asset compiler called Laravel Mix, which can be configured to handle the assets for both Laravel and Next.js. However, for simplicity, it’s recommended to let Next.js manage its own assets and to use Laravel Mix just for the Laravel side of things.

Authentication

authentication is key in any full-stack application. Laravel Sanctum can be used to provide a cookie-based session authentication for SPA, which works well with Next.js. Configuration involves setting the session domain and ensuring cookies are sent with every request:

// config/sanctum.php
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost:3000')), // add your Next.js development URL

// In the Next.js application, utilize Axios interceptors to send cookies
axios.defaults.withCredentials = true;

This configuration allows for seamless authentication between your Next.js frontend and the Laravel backend.

Running Both Servers

Start the Laravel development server:

php artisan serve

And in a new terminal, run the Next.js development server:

npm run dev

Navigate to http://localhost:3000 to view your Next.js frontend, and interact with your Laravel backend at http://localhost:8000.

Production Build and Deployment

For deploying the application, you’ll have two separate codebases to deploy. Traditionally, Next.js is deployed to platforms such Vercel or Netlify while Laravel can be deployed to a VPS or platforms like Laravel Forge.

Conclusion

The combination of Laravel and Next.js can create powerful full-stack applications. This guide has presented the foundational steps, but there are further optimizations and configurations you can implement as you become more familiar with the stack.