Laravel Breeze - Next.js Edition
repository·master·Indexed 23 days ago
https://github.com/laravel/breeze-nextA 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.
What's inside laravel-breeze-next
- 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.
Install Laravel Breeze - Next.js Edition
masterTo 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
apistack:# 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 migrateEnsure your
.envfile has the following environment variables set (usinglocalhostis recommended for local development to avoid CORS issues):APP_URL=http://localhost:8000FRONTEND_URL=http://localhost:3000
Start the backend server:
php artisan serve2. Configure the Next.js Frontend
Clone this repository, install dependencies, and configure the backend URL:
# Install dependencies npm install # or yarn installCopy
.env.exampleto.env.localand set theNEXT_PUBLIC_BACKEND_URLto match your Laravel backend:NEXT_PUBLIC_BACKEND_URL=http://localhost:8000Start the development server:
npm run devThe 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 migrateUse the useAuth hook for authentication
masterThe application provides a custom
useAuthReact 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
userobject, 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. Themiddlewareoption 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 ExamplePageUse the useAuth hook for authentication state and actions
masterThe
useAuthhook provides a centralized interface for managing user sessions, authentication state, and common authentication actions (register, login, logout, etc.) in a Next.js application. It usesSWRto fetch the current user from/api/userand handles CSRF protection automatically via/sanctum/csrf-cookiebefore performing state-changing requests.Authentication Actions
All action functions (like
loginorregister) accept an options object to handle validation errors and status updates:register({ setErrors, ...props }): Registers a new user.setErrorsis used to capture validation errors (HTTP 422).login({ setErrors, setStatus, ...props }): Authenticates a user.setErrorscaptures validation errors;setStatuscan 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/loginwith 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
useAuthto control automatic redirection logic viauseEffect:middleware:'guest': If the user is authenticated andredirectIfAuthenticatedis 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 (orundefined).register,login,forgotPassword,resetPassword,resendEmailVerification,logout: The action functions described above.
Use ResponsiveNavLink for navigation links
masterThe
ResponsiveNavLinkcomponent is a styled wrapper around Next.jsLinkdesigned for use in responsive navigation menus (such as mobile sidebars). It automatically applies active states based on theactiveprop, changing the border color, text color, and background color to indicate the current route.Props
active(boolean): Iftrue, applies the active styling (indigo theme). Defaults tofalse.children(ReactNode): The content to be rendered inside the link....props: Any other props supported by Next.jsLink(e.g.,href).
Use DropdownButton for actions within menus
masterTheDropdownButtoncomponent is a wrapper around a standard HTMLbuttondesigned for use within Headless UIMenucomponents. LikeDropdownLink, it handles theMenu.Itemlogic 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.Use ResponsiveNavButton for navigation actions
masterThe
ResponsiveNavButtoncomponent 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 withResponsiveNavLinkbut behaves as a standard button.Props
...props: All standard HTML button attributes.
Use DropdownLink for navigation within menus
masterTheDropdownLinkcomponent is a wrapper around Next.jsLinkdesigned for use within Headless UIMenucomponents. It automatically handles theMenu.Itemwrapper 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.