### Install and Run Development Server Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/README.md Install project dependencies using npm and start the development server. Access the application at http://localhost:3000. ```bash npm install npm run dev ``` -------------------------------- ### Production Environment Variable Example Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/configuration.md Example of setting the NEXT_PUBLIC_BACKEND_URL for a production environment. ```env NEXT_PUBLIC_BACKEND_URL=https://api.example.com ``` -------------------------------- ### Staging Environment Variable Example Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/configuration.md Example of setting the NEXT_PUBLIC_BACKEND_URL for a staging environment. ```env NEXT_PUBLIC_BACKEND_URL=https://staging-api.example.com ``` -------------------------------- ### Install Laravel Backend and Breeze API Scaffolding Source: https://github.com/laravel/breeze-next/blob/master/README.md Steps to create a new Laravel application, install Breeze with API scaffolding, and run database migrations. ```bash laravel new next-backend cd next-backend composer require laravel/breeze --dev php artisan breeze:install api php artisan migrate ``` -------------------------------- ### User Object Example Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/types-and-endpoints.md An example of the JSON response for an authenticated user, showing typical values for each field. ```json { "id": 1, "name": "John Doe", "email": "john@example.com", "email_verified_at": "2024-01-15T10:30:00Z", "created_at": "2024-01-10T08:00:00Z", "updated_at": "2024-01-15T10:30:00Z" } ``` -------------------------------- ### Login Request Example Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/axios-client.md Example of a POST request to the login endpoint, including headers and a JSON payload. ```http POST http://localhost:8000/login Content-Type: application/json X-Requested-With: XMLHttpRequest Cookie: XSRF-TOKEN=...; laravel_session=... { "email": "user@example.com", "password": "password", "remember": true } ``` -------------------------------- ### Custom Prettier Configuration Example Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/configuration.md Example of customizing Prettier settings by adding properties to .prettierrc.json. This example disables semicolons and sets trailing commas. ```json { "singleQuote": true, "semi": false, "trailingComma": "es5" } ``` -------------------------------- ### Login Success Response Example Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/axios-client.md Example of a successful login response, including Set-Cookie headers for session management. ```http Set-Cookie: laravel_session=... Set-Cookie: XSRF-TOKEN=... {} (empty object or user data) ``` -------------------------------- ### JavaScript Import Example with Alias Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/configuration.md Demonstrates using the '@/*' path alias for cleaner imports in JavaScript files. ```javascript // Instead of: import Button from '../../../components/Button' // Use: import Button from '@/components/Button' ``` -------------------------------- ### Login Form Example Usage Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/pages-authentication.md An example of how to use the login functionality within a form component. It demonstrates state management for email and password, and calls the `login` function from the `useAuth` hook upon form submission. ```javascript const LoginForm = () => { const { login } = useAuth({ middleware: 'guest', redirectIfAuthenticated: '/dashboard' }) const [email, setEmail] = useState('') const [password, setPassword] = useState('') const [errors, setErrors] = useState([]) const handleSubmit = (e) => { e.preventDefault() login({ email, password, remember: false, setErrors, setStatus: () => {} }) } return (
setEmail(e.target.value)} /> setPassword(e.target.value)} /> ) } ``` -------------------------------- ### Run Next.js Development Server Source: https://github.com/laravel/breeze-next/blob/master/README.md Command to start the Next.js development server. The application will be available at http://localhost:3000. ```bash npm run dev ``` -------------------------------- ### Create Production Build Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/README.md Execute these commands to create an optimized production build of your Next.js application and then start the production server. This is for deploying your application. ```bash npm run build npm start ``` -------------------------------- ### Dropdown Component Example Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/components-navigation.md Demonstrates how to use the Dropdown component with a custom trigger and a logout action. Ensure the DropdownButton is imported correctly. ```javascript import Dropdown from '@/components/Dropdown' import { DropdownButton } from '@/components/DropdownLink' const UserMenu = ({ userName }) => { return ( {userName} } > Logout ) } ``` -------------------------------- ### DropdownLink Component Example Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/components-navigation.md Shows how to integrate DropdownLink components within a Dropdown for navigation. Each DropdownLink uses the 'href' prop for routing. ```javascript import DropdownLink from '@/components/DropdownLink' import Dropdown from '@/components/Dropdown' const UserDropdown = () => { return ( Menu}> Dashboard Settings ) } ``` -------------------------------- ### Login Validation Error Response Example Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/axios-client.md Example of a 422 validation error response for the login request, detailing the specific fields with errors. ```json { "errors": { "email": ["The email field is required."], "password": ["The password field is required."] } } ``` -------------------------------- ### Error Object Example Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/types-and-endpoints.md An example of a validation error response, showing specific error messages for 'email' and 'password' fields. ```json { "email": ["The email field is required."], "password": ["The password must be at least 8 characters."] } ``` -------------------------------- ### Example Protected Dashboard Page Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/pages-protected.md This is an example of a protected page within the `(app)` route group. Authentication is handled by the layout component, so no explicit `useAuth` call is needed here. The user is guaranteed to be logged in and verified. ```javascript // src/app/(app)/dashboard/page.js import Header from '@/app/(app)/Header' const Dashboard = () => { // No need for useAuth here - handled by layout // User is guaranteed to exist and be verified return ( <>
You are logged in!
) } export default Dashboard ``` -------------------------------- ### Complete Login Form Example Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/components-form.md Integrates Label, Input, InputError, and Button components to create a functional login form. Handles form submission and displays validation errors. ```javascript 'use client' import Button from '@/components/Button' import Input from '@/components/Input' import InputError from '@/components/InputError' import Label from '@/components/Label' import { useAuth } from '@/hooks/auth' import { useState } from 'react' const LoginForm = () => { const { login } = useAuth({ middleware: 'guest', redirectIfAuthenticated: '/dashboard' }) const [email, setEmail] = useState('') const [password, setPassword] = useState('') const [errors, setErrors] = useState([]) const [status, setStatus] = useState(null) const handleSubmit = async (e) => { e.preventDefault() login({ email, password, setErrors, setStatus }) } return (
{/* Email Field */}
setEmail(e.target.value)} className="block w-full mt-1" required autoFocus />
{/* Password Field */}
setPassword(e.target.value)} className="block w-full mt-1" required />
{/* Submit */}
) } export default LoginForm ``` -------------------------------- ### Example Laravel CORS Middleware Configuration Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/configuration.md Provides a sample configuration for Laravel's CORS middleware to allow requests from the Next.js frontend. ```php // config/cors.php 'paths' => ['api/*', 'login', 'register', 'logout', 'sanctum/csrf-cookie'], 'allowed_origins' => ['http://localhost:3000'], 'allowed_methods' => ['*'], 'allowed_headers' => ['*'], 'supports_credentials' => true, ``` -------------------------------- ### Creating a Protected Settings Page Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/pages-protected.md Example of creating a protected page that requires authentication. It imports a Header component and optionally uses a useAuth hook to access user data. ```javascript 'use client' import Header from '@/app/(app)/Header' import { useAuth } from '@/hooks/auth' const SettingsPage = () => { const { user } = useAuth({ middleware: 'auth' }) return ( <>

Account Settings

{/* Settings form */}
) } export default SettingsPage ``` -------------------------------- ### Perform API Requests with Axios Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/00-START-HERE.md Demonstrates making GET and POST requests to your API using the configured Axios instance. Includes basic error handling for unauthorized and validation errors. ```javascript import axios from '@/lib/axios' // GET request const fetchUser = async () => { try { const { data } = await axios.get('/api/user') console.log(data) // { id, name, email, ... } } catch (error) { if (error.response?.status === 401) { // Not authenticated } } } // POST request const updateProfile = async (name) => { try { await axios.post('/api/profile', { name }) } catch (error) { if (error.response?.status === 422) { // Validation error console.log(error.response.data.errors) } } } ``` -------------------------------- ### User Fetch Request and Response Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/axios-client.md Demonstrates the GET request to fetch the authenticated user's data and the structure of the success and unauthorized responses. ```APIDOC ## GET /api/user ### Description Fetches the details of the currently authenticated user. ### Method GET ### Endpoint /api/user ### Request Example ```http GET http://localhost:8000/api/user X-Requested-With: XMLHttpRequest Cookie: laravel_session=...; XSRF-TOKEN=... ``` ### Response #### Success Response (2xx) Returns a JSON object containing the user's details. - **id** (integer) - The user's unique identifier. - **name** (string) - The user's full name. - **email** (string) - The user's email address. - **email_verified_at** (string) - The timestamp when the email was verified. - **created_at** (string) - The timestamp when the user was created. - **updated_at** (string) - The timestamp when the user was last updated. ```json { "id": 1, "name": "John Doe", "email": "john@example.com", "email_verified_at": "2024-01-15T10:30:00Z", "created_at": "2024-01-10T08:00:00Z", "updated_at": "2024-01-15T10:30:00Z" } ``` #### Unauthorized Response (401) Returned if the user is not authenticated. ```json { "message": "Unauthenticated." } ``` ``` -------------------------------- ### Basic GET Request Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/axios-client.md Perform a basic GET request to fetch user data from the '/api/user' endpoint. Handles potential authentication errors. ```javascript import axios from '@/lib/axios' const fetchUser = async () => { try { const response = await axios.get('/api/user') console.log(response.data) // User object } catch (error) { if (error.response?.status === 401) { // Not authenticated } } } ``` -------------------------------- ### Form Components Example Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/00-START-HERE.md Basic usage of form input components, including labels, text inputs, error display, and buttons. These components are styled with Tailwind CSS. ```javascript ``` -------------------------------- ### Package.json Scripts for Next.js Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/configuration.md Defines common scripts for managing a Next.js application, including development, building, starting, and linting. ```json { "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint", "lint:fix": "next lint --fix" } } ``` -------------------------------- ### CSRF Cookie Request Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/types-and-endpoints.md Demonstrates the HTTP GET request to fetch the CSRF token. This is a prerequisite for subsequent write operations to ensure security. ```http GET /sanctum/csrf-cookie ``` -------------------------------- ### DropdownButton Component Example Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/components-navigation.md Illustrates using DropdownButton for actions within a dropdown menu, such as a logout function. The onClick handler is passed as a prop. ```javascript import { DropdownButton } from '@/components/DropdownLink' const UserMenu = ({ onLogout }) => { return ( Menu}> Logout ) } ``` -------------------------------- ### HTTP Request with Axios Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/00-START-HERE.md Making a GET request to fetch user data using the pre-configured Axios client. This client includes CSRF protection and cookie handling. ```javascript import axios from '@/lib/axios' const { data } = await axios.get('/api/user') ``` -------------------------------- ### AuthSessionStatus Component Example Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/components-layout.md Shows how to use AuthSessionStatus to display messages like password reset confirmations. It accepts a status message and optional CSS classes. This component integrates with hooks like `useAuth`. ```javascript import AuthSessionStatus from '@/app/(auth)/AuthSessionStatus' import Button from '@/components/Button' import { useAuth } from '@/hooks/auth' import { useState } from 'react' const ForgotPasswordPage = () => { const { forgotPassword } = useAuth({ middleware: 'guest', redirectIfAuthenticated: '/dashboard' }) const [email, setEmail] = useState('') const [status, setStatus] = useState(null) const handleSubmit = (e) => { e.preventDefault() forgotPassword({ email, setErrors: () => {}, setStatus }) } return (
setEmail(e.target.value)} />
) } ``` -------------------------------- ### Axios Instance Configuration Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/axios-client.md Configure the Axios instance with the backend URL, request headers, and options for sending credentials and XSRF tokens. ```javascript const axios = Axios.create({ baseURL: process.env.NEXT_PUBLIC_BACKEND_URL, headers: { 'X-Requested-With': 'XMLHttpRequest', }, withCredentials: true, withXSRFToken: true }) ``` -------------------------------- ### Get Authenticated User Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/_DOCUMENTATION_SUMMARY.txt Retrieves the currently authenticated user's information. ```APIDOC ## GET /api/user ### Description Retrieves the currently authenticated user's information. ### Method GET ### Endpoint /api/user ### Parameters None ### Request Example None ### Response #### Success Response (200 OK) - **id** (integer) - The user's unique identifier. - **name** (string) - The user's name. - **email** (string) - The user's email address. - **email_verified_at** (string|null) - The timestamp when the email was verified, or null if not verified. - **created_at** (string) - The timestamp when the user was created. - **updated_at** (string) - The timestamp when the user was last updated. #### Response Example ```json { "id": 1, "name": "John Doe", "email": "john.doe@example.com", "email_verified_at": "2026-06-15T10:00:00.000000Z", "created_at": "2026-06-15T09:00:00.000000Z", "updated_at": "2026-06-15T09:00:00.000000Z" } ``` ``` -------------------------------- ### Get Authenticated User Request Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/types-and-endpoints.md Fetches the currently authenticated user. Requires authentication headers. ```http GET /api/user X-Requested-With: XMLHttpRequest Cookie: laravel_session=...; XSRF-TOKEN=... ``` -------------------------------- ### Configure Middleware Behavior for Authentication Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/00-START-HERE.md Shows how to configure the `useAuth` hook for different middleware requirements. Options include 'auth', 'guest' with redirects, or no enforcement. ```javascript // Requires authentication, redirects to /login if not useAuth({ middleware: 'auth' }) // Requires guest, redirects to /dashboard if authenticated useAuth({ middleware: 'guest', redirectIfAuthenticated: '/dashboard' }) // No enforcement, shows different content based on state useAuth() ``` -------------------------------- ### Serve Laravel Backend Source: https://github.com/laravel/breeze-next/blob/master/README.md Command to serve the Laravel backend application using the Artisan serve command. ```bash php artisan serve ``` -------------------------------- ### Login Endpoint Unauthenticated Response Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/types-and-endpoints.md Example of a 401 Unauthorized response from the /login endpoint, typically returned when authentication fails. ```json { "message": "Unauthenticated." } ``` -------------------------------- ### Protected Page Structure Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/00-START-HERE.md Example of a protected page component, 'Dashboard', which includes a Header. The layout automatically enforces authentication. ```javascript // src/app/(app)/dashboard/page.js import Header from '@/app/(app)/Header' const Dashboard = () => { return <>
{/* content */} } ``` -------------------------------- ### User Login Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/_DOCUMENTATION_SUMMARY.txt Authenticates a user and establishes a session. ```APIDOC ## POST /login ### Description Authenticates a user and establishes a session. ### Method POST ### Endpoint /login ### Parameters #### Request Body - **email** (string) - Required - The email address of the user. - **password** (string) - Required - The password for the user. - **remember** (boolean) - Optional - Whether to remember the user's session. ### Request Example ```json { "email": "john.doe@example.com", "password": "password123", "remember": true } ``` ### Response #### Success Response (200 OK) - **message** (string) - A success message indicating the user was logged in. #### Response Example ```json { "message": "User logged in successfully." } ``` ``` -------------------------------- ### Login Endpoint Validation Error Response Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/types-and-endpoints.md Example of a 422 Unprocessable Entity response from the /login endpoint, indicating invalid credentials. ```json { "message": "The given data was invalid.", "errors": { "email": ["These credentials do not match our records."] } } ``` -------------------------------- ### Register User with useAuth Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/hooks-auth.md Use the register method to create a new user account. Pass state setters for errors and user details. Requires CSRF cookie fetch before POSTing to /register. ```javascript const { register } = useAuth({ middleware: 'guest', redirectIfAuthenticated: '/dashboard' }) const [name, setName] = useState('') const [email, setEmail] = useState('') const [password, setPassword] = useState('') const [passwordConfirmation, setPasswordConfirmation] = useState('') const [errors, setErrors] = useState([]) const handleRegister = () => { register({ name, email, password, password_confirmation: passwordConfirmation, setErrors }) } ``` -------------------------------- ### register Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/hooks-auth.md Registers a new user account with the provided details. ```APIDOC ## register ### Description Registers a new user account. ### Signature ```javascript register({ setErrors, ...props }) ``` ### Parameters #### Path Parameters - **name** (`string`) - Required - User full name - **email** (`string`) - Required - User email address - **password** (`string`) - Required - User password - **password_confirmation** (`string`) - Required - Password confirmation for validation - **setErrors** (`function`) - Required - State setter for validation errors (receives object with keys matching failed fields) ### Process 1. Fetches CSRF token from `/sanctum/csrf-cookie` 2. POSTs to `/register` with user data 3. On success: calls `mutate()` to refresh user state and redirects via middleware 4. On 422 validation error: populates errors via `setErrors(error.response.data.errors)` 5. Other errors: re-thrown to caller ### Request Example ```javascript const { register } = useAuth({ middleware: 'guest', redirectIfAuthenticated: '/dashboard' }) const [name, setName] = useState('') const [email, setEmail] = useState('') const [password, setPassword] = useState('') const [passwordConfirmation, setPasswordConfirmation] = useState('') const [errors, setErrors] = useState([]) const handleRegister = () => { register({ name, email, password, password_confirmation: passwordConfirmation, setErrors }) } ``` ``` -------------------------------- ### Basic Next.js Configuration Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/configuration.md A basic structure for a custom next.config.js file. Create this file to add custom Next.js configuration. ```javascript /** @type {import('next').NextConfig} */ const nextConfig = { // Custom configuration } module.exports = nextConfig ``` -------------------------------- ### Build a Login Form with State Management Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/00-START-HERE.md Implement a login form using React state for email and password. Handles form submission and error display. Requires 'guest' middleware and redirects if authenticated. ```javascript // src/app/(auth)/login/page.js 'use client' import Button from '@/components/Button' import Input from '@/components/Input' import InputError from '@/components/InputError' import Label from '@/components/Label' import { useAuth } from '@/hooks/auth' import { useState } from 'react' const LoginPage = () => { const [email, setEmail] = useState('') const [password, setPassword] = useState('') const [errors, setErrors] = useState([]) const { login } = useAuth({ middleware: 'guest', redirectIfAuthenticated: '/dashboard' }) const handleSubmit = (e) => { e.preventDefault() login({ email, password, setErrors, setStatus: () => {} }) } return (
setEmail(e.target.value)} className="block w-full mt-1" required />
setPassword(e.target.value)} className="block w-full mt-1" required />
) } export default LoginPage ``` -------------------------------- ### Registration Flow: Fetch User Data Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/types-and-endpoints.md Fetches the user object after registration to verify the process. This confirms the user has been created and is available. ```http GET /api/user ↓ User object returned ``` -------------------------------- ### Typical Page Structure with Header Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/components-layout.md Demonstrates a standard page layout using a Header component for titles and nested content within a max-width container. This pattern is suitable for content-heavy pages like settings. ```javascript // src/app/(app)/settings/page.js import Header from '@/app/(app)/Header' const SettingsPage = () => { return ( <>
{/* Settings form */}
) } export default SettingsPage ``` -------------------------------- ### Tailwind CSS Theme Customization Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/configuration.md Example of extending the Tailwind CSS theme with custom colors and spacing. This allows for more specific design system implementation. ```javascript module.exports = { content: ['./src/**/*.{js,jsx,ts,tsx}'], theme: { extend: { colors: { brand: '#FF6B6B', }, spacing: { '128': '32rem', }, }, }, plugins: [require('@tailwindcss/forms')], } ``` -------------------------------- ### Login Flow: Fetch CSRF Token Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/types-and-endpoints.md Initiates the login process by fetching a CSRF token from the server. This is the first step before submitting login credentials. ```http GET /sanctum/csrf-cookie ↓ Set-Cookie: XSRF-TOKEN=... ``` -------------------------------- ### Fetch CSRF Token Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/axios-client.md Acquire a CSRF token by making a GET request to '/sanctum/csrf-cookie'. Axios automatically handles storing this token for subsequent requests. ```javascript import axios from '@/lib/axios' // Fetch CSRF token before write operations const getCsrfToken = async () => { await axios.get('/sanctum/csrf-cookie') // Token is now in cookies, automatically sent by axios } ``` -------------------------------- ### Register Endpoint Validation Error Response Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/types-and-endpoints.md Example of a 422 Unprocessable Entity response from the /register endpoint, detailing validation errors for email and password fields. ```json { "message": "The given data was invalid.", "errors": { "email": ["The email has already been taken."], "password": ["The password confirmation does not match."] } } ``` -------------------------------- ### login Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/hooks-auth.md Authenticates a user with their email and password. ```APIDOC ## login ### Description Authenticates user with email and password. ### Signature ```javascript login({ setErrors, setStatus, ...props }) ``` ### Parameters #### Path Parameters - **email** (`string`) - Required - User email address - **password** (`string`) - Required - User password - **remember** (`boolean`) - Optional - Whether to set remember-me cookie - **setErrors** (`function`) - Required - State setter for validation errors - **setStatus** (`function`) - Required - State setter for status messages ### Process 1. Fetches CSRF token from `/sanctum/csrf-cookie` 2. POSTs to `/login` with credentials 3. On success: calls `mutate()` to refresh user and redirects via middleware 4. On 422 validation error: populates errors 5. Sets `setStatus(null)` before request 6. Other errors: re-thrown to caller ### Request Example ```javascript const { login } = useAuth({ middleware: 'guest', redirectIfAuthenticated: '/dashboard' }) const [email, setEmail] = useState('') const [password, setPassword] = useState('') const [errors, setErrors] = useState([]) const [status, setStatus] = useState(null) const handleLogin = async (e) => { e.preventDefault() login({ email, password, setErrors, setStatus }) } ``` ``` -------------------------------- ### ApplicationLogo Component Examples Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/components-layout.md Render the ApplicationLogo component with different Tailwind CSS classes to control its size and color. This component is a versatile SVG for branding within the application. ```javascript import ApplicationLogo from '@/components/ApplicationLogo' // In auth pages // In navigation // Custom size and color ``` -------------------------------- ### Guest Page Middleware Configuration Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/README.md Configure the `useAuth` hook for guest-only pages like login or registration. It redirects authenticated users to the dashboard. ```javascript useAuth({ middleware: 'guest', redirectIfAuthenticated: '/dashboard' }) ``` -------------------------------- ### User Registration Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/_DOCUMENTATION_SUMMARY.txt Registers a new user account. ```APIDOC ## POST /register ### Description Registers a new user account. ### Method POST ### Endpoint /register ### Parameters #### Request Body - **name** (string) - Required - The name of the user. - **email** (string) - Required - The email address of the user. - **password** (string) - Required - The password for the new account. - **password_confirmation** (string) - Required - The password confirmation. ### Request Example ```json { "name": "John Doe", "email": "john.doe@example.com", "password": "password123", "password_confirmation": "password123" } ``` ### Response #### Success Response (200 OK) - **message** (string) - A success message indicating the user was registered. #### Response Example ```json { "message": "User registered successfully." } ``` ``` -------------------------------- ### Create a Protected Page Component Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/INDEX.md Define a protected page component in Next.js. This example shows a basic structure for a page that might require authentication, including importing a Header component. ```javascript // File: src/app/(app)/mypage/page.js import Header from '@/app/(app)/Header' const MyPage = () => { return ( <>
{/* Content */} ) } ``` -------------------------------- ### Run Linting Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/README.md Use these npm commands to check your code for style and potential errors using ESLint. The `lint:fix` command attempts to automatically correct most linting issues. ```bash npm run lint npm run lint:fix ``` -------------------------------- ### Handle Form Submission with Validation Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/README.md Implement form submissions using the `login` function from `useAuth`. This function accepts an object with credentials and callbacks for handling errors and status updates. Ensure you manage the `email` state and provide a password. ```javascript const [email, setEmail] = useState('') const [errors, setErrors] = useState([]) const { login } = useAuth() const handleSubmit = (e) => { e.preventDefault() login({ email, password: '...', setErrors, setStatus: () => {} }) } return (
setEmail(e.target.value)} /> ) ``` -------------------------------- ### Runtime Dependencies for Next.js App Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/configuration.md Lists essential packages for running a Next.js application, including the framework itself, UI libraries, and data fetching tools. ```json { "@headlessui/react": "^1.4.2", "axios": "^0.32.0", "next": "^14.2.10", "react": "^18.2.0", "react-dom": "^18.2.0", "swr": "^1.3.0" } ``` -------------------------------- ### Use useAuth Hook in Next.js Component Source: https://github.com/laravel/breeze-next/blob/master/README.md Example of using the custom useAuth hook to access user data and the logout function within a React component. Use optional chaining for user properties. ```javascript const ExamplePage = () => { const { logout, user } = useAuth({ middleware: 'auth' }) return ( <>

{user?.name}

) } export default ExamplePage ``` -------------------------------- ### Login Endpoint Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/types-and-endpoints.md Authenticates an existing user and establishes a session. This endpoint is used for user login with email and password. ```APIDOC ## POST /login ### Description Authenticates a user and creates a session. Requires a valid CSRF token in the request headers. ### Method POST ### Endpoint /login ### Parameters #### Request Body - **email** (string) - Required - User's email address - **password** (string) - Required - User's password - **remember** (boolean) - Optional - If true, extends the session lifetime ### Request Example ```json { "email": "john@example.com", "password": "password123", "remember": true } ``` ### Response #### Success Response (200 OK) An empty JSON object `{}` is returned upon successful login. Session and authentication cookies are automatically set. #### Response Example ```json {} ``` #### Validation Error Response (422 Unprocessable Entity) Returned when the provided credentials do not match records. ### Response Example ```json { "message": "The given data was invalid.", "errors": { "email": ["These credentials do not match our records."] } } ``` #### Unauthenticated Response (401 Unauthorized) Returned when authentication fails. ### Response Example ```json { "message": "Unauthenticated." } ``` ### Used by `useAuth` → `login()` method ``` -------------------------------- ### Access User in Shared Components Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/README.md Use the `useAuth` hook to get user data in components that are shared across your application. This hook is designed for use in components that might be rendered without forced redirects. ```javascript const { user } = useAuth() ``` -------------------------------- ### Login Endpoint Request Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/types-and-endpoints.md Illustrates the POST request format for the /login endpoint, including authentication credentials and an optional 'remember' flag. ```http POST /login Content-Type: application/json X-Requested-With: XMLHttpRequest X-XSRF-TOKEN: {token} { "email": "john@example.com", "password": "password123", "remember": true } ``` -------------------------------- ### Example Validation Errors Response Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/README.md When a validation error occurs (HTTP 422), the API returns a JSON object with an `errors` key. This object contains field-specific error messages that can be accessed and displayed in your frontend components. ```json { "errors": { "email": ["Email already exists"], "password": ["Password too short"] } } ``` -------------------------------- ### Configuring Google Fonts in Next.js Layout Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/configuration.md Demonstrates how to import and apply Google Fonts (Nunito) to the root HTML element in a Next.js application for consistent typography. ```javascript import { Nunito } from 'next/font/google' const nunitoFont = Nunito({ subsets: ['latin'], display: 'swap', }) // Applied to element ``` -------------------------------- ### Email Verification Page Component (Usage Example) Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/pages-authentication.md This React component handles the email verification process. It allows users to resend verification emails and provides feedback on the status. It also includes a logout option and redirects to /dashboard upon successful verification. ```javascript const VerifyEmailPage = () => { const { logout, resendEmailVerification } = useAuth({ middleware: 'auth', redirectIfAuthenticated: '/dashboard' }) const [status, setStatus] = useState(null) const handleResendClick = () => { resendEmailVerification({ setStatus }) } const handleLogoutClick = () => { logout() } return (

Please verify your email address before continuing.

{status === 'verification-link-sent' && (
A new verification link has been sent.
)}
) } ``` -------------------------------- ### Login User with useAuth Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/hooks-auth.md Use the login method to authenticate a user. Pass state setters for errors and status messages. Requires CSRF cookie fetch before POSTing to /login. ```javascript const { login } = useAuth({ middleware: 'guest', redirectIfAuthenticated: '/dashboard' }) const [email, setEmail] = useState('') const [password, setPassword] = useState('') const [errors, setErrors] = useState([]) const [status, setStatus] = useState(null) const handleLogin = async (e) => { e.preventDefault() login({ email, password, setErrors, setStatus }) } ``` -------------------------------- ### Register Endpoint Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/types-and-endpoints.md Creates a new user account. This endpoint handles the registration process, including validation of user credentials. ```APIDOC ## POST /register ### Description Creates a new user account. Requires a valid CSRF token in the request headers. ### Method POST ### Endpoint /register ### Parameters #### Request Body - **name** (string) - Required - User's full name - **email** (string) - Required - User's email address (must be unique) - **password** (string) - Required - User's password - **password_confirmation** (string) - Required - User's password confirmation ### Request Example ```json { "name": "John Doe", "email": "john@example.com", "password": "password123", "password_confirmation": "password123" } ``` ### Response #### Success Response (201 Created) An empty JSON object `{}` is returned upon successful registration. Session and auth cookies are automatically set. #### Response Example ```json {} ``` #### Validation Error Response (422 Unprocessable Entity) Returned when the provided data is invalid. Contains a field-keyed object of error messages. ### Response Example ```json { "message": "The given data was invalid.", "errors": { "email": ["The email has already been taken."], "password": ["The password confirmation does not match."] } } ``` ### Used by `useAuth` → `register()` method ``` -------------------------------- ### App Layout with Loading Indicator Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/components-layout.md Integrate the Loading component into your main application layout to manage the initial data fetching state for authenticated users. This ensures a smooth user experience by showing the loader until user data is available. ```javascript 'use client' import { useAuth } from '@/hooks/auth' import Navigation from '@/app/(app)/Navigation' import Loading from '@/app/(app)/Loading' const AppLayout = ({ children }) => { const { user } = useAuth({ middleware: 'auth' }) if (!user) { return } return (
{children}
) } export default AppLayout ``` -------------------------------- ### Configure Next.js Frontend Environment Source: https://github.com/laravel/breeze-next/blob/master/README.md Set the NEXT_PUBLIC_BACKEND_URL environment variable in .env.local for the Next.js frontend to connect to the Laravel backend. ```dotenv NEXT_PUBLIC_BACKEND_URL=http://localhost:8000 ``` -------------------------------- ### Use Auth Hook Configuration Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/00-START-HERE.md The `useAuth` hook centralizes all authentication methods. Configure it with a middleware ('auth', 'guest', or none) and a redirect path for authenticated users. ```javascript const { user, login, register, logout } = useAuth({ middleware: 'auth', // 'auth', 'guest', or none redirectIfAuthenticated: '/dashboard' }) ``` -------------------------------- ### Create a Protected Page Component Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/00-START-HERE.md Defines a settings page component that is protected by authentication middleware. The layout ensures the user is authenticated before rendering. ```javascript // src/app/(app)/settings/page.js import Header from '@/app/(app)/Header' const SettingsPage = () => { // Layout already enforces middleware: 'auth' // User is guaranteed to be authenticated return ( <>
{/* Your content */}
) } export default SettingsPage ``` -------------------------------- ### Development Dependencies for Next.js Project Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/configuration.md Includes packages required for development, such as linters, formatters, CSS frameworks, and build tools. ```json { "@babel/eslint-parser": "^7.12.1", "@babel/preset-react": "^7.18.6", "@next/eslint-plugin-next": "^14.2.3", "@tailwindcss/forms": "^0.5.2", "autoprefixer": "^10.4.2", "eslint": "^8.27.0", "eslint-config-next": "^14.0.3", "eslint-config-prettier": "^7.2.0", "postcss": "^8.5.10", "prettier": "^3.2.5", "tailwindcss": "^3.4.3" } ``` -------------------------------- ### Navigation with Active State Indication Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/INDEX.md Create navigation links that visually indicate the active state based on the current URL path. The `usePathname` hook helps determine the current path for comparison. ```javascript const pathname = usePathname() Dashboard ``` -------------------------------- ### App Layout Component Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/pages-protected.md This client component enforces authentication using the `useAuth` hook with `middleware: 'auth'`. It displays a loading state while fetching user data and renders a navigation bar and main content area once authenticated. ```javascript 'use client' import { useAuth } from '@/hooks/auth' import Navigation from '@/app/(app)/Navigation' import Loading from '@/app/(app)/Loading' const AppLayout = ({ children }) => { const { user } = useAuth({ middleware: 'auth' }) if (!user) { return } return (
{children}
) } ``` -------------------------------- ### Pages/Routes Documentation Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/_DOCUMENTATION_SUMMARY.txt Information on accessing documentation for different page and route groups, specifically authentication-related routes and protected application routes. ```APIDOC ## Pages and Routes ### Description Documentation for the application's pages and routes is organized into logical groups. Users can find information on authentication-related routes in `pages-authentication.md` and details on protected application routes in `pages-protected.md`. ### Accessing Route Documentation - **Authentication Routes**: Consult `pages-authentication.md` for documentation on public-facing authentication pages (e.g., login, register). - **Protected Routes**: Consult `pages-protected.md` for documentation on routes that require user authentication. ``` -------------------------------- ### Default Prettier Configuration Source: https://github.com/laravel/breeze-next/blob/master/_autodocs/configuration.md An empty .prettierrc.json file indicates that Prettier will use all its default settings. This includes 2-space indentation and single quotes. ```json {} ```