Laravel Breeze - Next.js Edition

repository·master·Indexed 23 days ago

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

A frontend implementation of the Laravel Breeze authentication starter kit using Next.js. It provides a ready-to-use authentication boilerplate powered by Laravel Sanctum, featuring a custom useAuth hook for session management, Ziggy for Laravel named route referencing, and a set of responsive UI components for navigation and menus.

Tokens
1.7K
Snippets
2
Records
8
Agent score
82%

What's inside laravel-breeze-next

  1. Reference Laravel named routes in Next.js

    master
    This project uses Ziggy to allow you to reference your Laravel application's named routes directly from your React components. This enables seamless URL generation that stays in sync with your backend routing configuration.
  2. Install Laravel Breeze - Next.js Edition

    master

    To set up the full stack, you must first configure a Laravel backend with API scaffolding and then set up the Next.js frontend.

    1. Configure the Laravel Backend

    Create a new Laravel application and install Breeze with the api stack:

    # Create the Laravel application
    laravel new next-backend
    
    cd next-backend
    
    # Install Breeze and dependencies
    composer require laravel/breeze --dev
    
    # Install the API scaffolding
    php artisan breeze:install api
    
    # Run database migrations
    php artisan migrate

    Ensure your .env file has the following environment variables set (using localhost is recommended for local development to avoid CORS issues):

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

    Start the backend server:

    php artisan serve

    2. Configure the Next.js Frontend

    Clone this repository, install dependencies, and configure the backend URL:

    # Install dependencies
    npm install
    # or
    yarn install

    Copy .env.example to .env.local and set the NEXT_PUBLIC_BACKEND_URL to match your Laravel backend:

    NEXT_PUBLIC_BACKEND_URL=http://localhost:8000

    Start the development server:

    npm run dev

    The application will be available at http://localhost:3000.

    # Create the Laravel application...
    laravel new next-backend
    
    cd next-backend
    
    # Install Breeze and dependencies...
    composer require laravel/breeze --dev
    
    php artisan breeze:install api
    
    # Run database migrations...
    php artisan migrate
  3. Use the useAuth hook for authentication

    master

    The application provides a custom useAuth React hook that abstracts all authentication logic. It allows you to manage user sessions and access the currently authenticated user object.

    When accessing properties on the user object, use optional chaining (e.g., user?.name) to prevent errors during Next.js's initial server-side rendering when the user state might be null.

    Hook Signature/Usage:

    • useAuth({ middleware: 'auth' }): Initializes the hook. The middleware option can be used to enforce authentication requirements.
    • Returns logout: A function to sign the user out.
    • Returns user: The authenticated user object.
    const ExamplePage = () => {
        const { logout, user } = useAuth({ middleware: 'auth' })
    
        return (
            <>
                <p>{user?.name}</p>
    
                <button onClick={logout}>Sign out</button>
            </>
        )
    }
    
    export default ExamplePage
  4. Use the useAuth hook for authentication state and actions

    master

    The useAuth hook provides a centralized interface for managing user sessions, authentication state, and common authentication actions (register, login, logout, etc.) in a Next.js application. It uses SWR to fetch the current user from /api/user and handles CSRF protection automatically via /sanctum/csrf-cookie before performing state-changing requests.

    Authentication Actions

    All action functions (like login or register) accept an options object to handle validation errors and status updates:

    • register({ setErrors, ...props }): Registers a new user. setErrors is used to capture validation errors (HTTP 422).
    • login({ setErrors, setStatus, ...props }): Authenticates a user. setErrors captures validation errors; setStatus can be used to manage UI status messages.
    • forgotPassword({ setErrors, setStatus, email }): Initiates the password recovery process.
    • resetPassword({ setErrors, setStatus, ...props }): Resets the password using a token from the URL parameters. On success, it redirects to /login with a base64 encoded status.
    • resendEmailVerification({ setStatus }): Requests a new email verification link.
    • logout(): Logs the user out and redirects to /login.

    Middleware and Redirection

    You can pass configuration options to useAuth to control automatic redirection logic via useEffect:

    • middleware:
      • 'guest': If the user is authenticated and redirectIfAuthenticated is provided, the user is redirected to the specified path.
      • 'auth': If the user is not authenticated (error exists), they are logged out. If the user is authenticated but has not verified their email, they are redirected to /verify-email.
    • redirectIfAuthenticated: The path to redirect to if a 'guest' middleware user is found to be authenticated.

    Returned Values

    The hook returns an object containing:

    • user: The current user data (or undefined).
    • register, login, forgotPassword, resetPassword, resendEmailVerification, logout: The action functions described above.
  5. Use ResponsiveNavLink for navigation links

    master

    The ResponsiveNavLink component is a styled wrapper around Next.js Link designed for use in responsive navigation menus (such as mobile sidebars). It automatically applies active states based on the active prop, changing the border color, text color, and background color to indicate the current route.

    Props

    • active (boolean): If true, applies the active styling (indigo theme). Defaults to false.
    • children (ReactNode): The content to be rendered inside the link.
    • ...props: Any other props supported by Next.js Link (e.g., href).
  6. Use DropdownButton for actions within menus

    master
    The DropdownButton component is a wrapper around a standard HTML button designed for use within Headless UI Menu components. Like DropdownLink, it handles the Menu.Item logic and applies consistent dropdown styling and active states. Use this when you want a menu item to trigger a function (like a logout action) rather than navigating to a new page.
  7. Use ResponsiveNavButton for navigation actions

    master

    The ResponsiveNavButton component is a styled <button> element intended for navigation-related actions that do not require a direct URL link (e.g., triggering a logout or opening a sub-menu). It shares similar visual styling with ResponsiveNavLink but behaves as a standard button.

    Props

    • ...props: All standard HTML button attributes.
  8. Use DropdownLink for navigation within menus

    master
    The DropdownLink component is a wrapper around Next.js Link designed for use within Headless UI Menu components. It automatically handles the Menu.Item wrapper and applies consistent styling for dropdown items, including a hover/active state (bg-gray-100). Use this when you want a menu item to navigate to a different route.