# Auth0 Next.js v4 setup

Install `@auth0/nextjs-auth0` v4. v3 samples you find online (withPageAuthRequired, handleAuth in pages/api) do not apply.

## 1. Env vars

Create `.env.local` at the project root. Fill every one of these in:

```
AUTH0_DOMAIN YOUR-TENANT-DOMAIN
AUTH0_CLIENT_ID [your value]
AUTH0_CLIENT_SECRET [your value]
AUTH0_SECRET [your value]
APP_BASE_URL [your app base URL]
```

Generate the session secret value `openssl rand -hex 32`. AUTH0_SECRET encrypts the session cookie. Short or missing secret is the most common local breakage.

## 2. SDK client

Create `lib/auth0.ts`:

```
import { Auth0Client } from "@auth0/nextjs-auth0/server";
export const auth0 = new Auth0Client();
```

## 3. Middleware

Create `middleware.ts` at the project root:

```
import { auth0 } from "./lib/auth0";
export async function middleware(request) {
  return await auth0.middleware(request);
}
export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)"],
};
```

The middleware refreshes the session on every request and makes it available server-side.

## 4. Auth routes

The SDK serves `/auth/login`, `/auth/logout`, and `/auth/callback` from the middleware. Register Allowed Callback URLs in the dashboard as `APP_BASE_URL` + `/auth/callback`, exact match, no trailing slash mismatch.

## 5. Read the session

Server components and route handlers:

```
import { auth0 } from "@/lib/auth0";
import { redirect } from "next/navigation";

export default async function ProtectedPage() {
  const session = await auth0.getSession();
  if (!session) redirect("/auth/login");
  return [h1]hi {session.user.name}[/h1];
}
```

In v4 the Auth0Provider is optional; only add it if you want the initial user on the client for the useUser hook.

## Checklist

- Application type is Regular Web Application in the dashboard.
- Callback URL registered exactly, including port.
- AUTH0_SECRET is 32+ bytes and stable across restarts (do not regenerate per deploy or sessions die).