Laravel with Next JS Boilerplate Project

I am looking at getting started with Laravel back end and Front End with React Next JS.

I found an excellent Github repository on how to start this project. So here are the steps to get started.

1. Install a new version of Laravel into a directory

composer create-project laravel/laravel example-app

cd example-app

2. Install Laravel Breeze (Breeze allows you for easy authentication API calls.

# Install Breeze and dependencies...
composer require laravel/breeze

php artisan breeze:install api

3. In your .env file ensure you set APP_URL and FRONTEND_URL environments set to:

APP_URL=http://localhost:8000
FRONTEND_URL=http://localhost:3000

If you want to change your localhost path you can do it here.

4. Launch Laravel backend

# Serve the application...
php artisan serve

5. Next you will clone the Next JS frontend.

https://github.com/laravel/breeze-next

6. Now install all dependencies via yarn or npm

yarn install 
or 
npm install

7. Rename .env.examble to .env.local and

8. Make sure inside your .env.local you have your backend URL

NEXT_PUBLIC_BACKEND_URL=http://localhost:8000

9. Now you can run your application.

npm run dev

if you would like to use another domain apart from localhost remember that you need to enable CORS.

Authentication Hook

This Next.js application contains a custom useAuth React hook, is designed to abstract all authentication logic away from your pages. In addition, the hook can be used to access the currently authenticated user:

const ExamplePage = () => {
    const { logout, user } = useAuth({ middleware: 'auth' })

    return (
        <>
            <p>{user?.name}</p>

            <button onClick={logout}>Sign out</button>
        </>
    )
}

export default ExamplePage

Note: You will need to use optional chaining (user?.name instead of user.name) when accessing properties on the user object to account for Next.js’s initial server-side render.