> Install @pylo/auth-nextjs and protect routes with the auth middleware

# Next.js Setup

`@pylo/auth-nextjs` handles user authentication for Next.js: login, logout, session management, and
automatic token refresh.

## Install

```bash
# pnpm
pnpm add @pylo/auth-nextjs
# npm
npm install @pylo/auth-nextjs
# yarn
yarn add @pylo/auth-nextjs
```

## Environment

```bash filename=".env.local"
PYLO_APP_ID=your-app-id
```

`PYLO_APP_ID` scopes the auth cookies per app. Find your app id in **Settings > Apps** in the admin
panel.

## Middleware

Create a `proxy.ts` in your project root:

```typescript filename="proxy.ts"
import { createPyloProxy } from "@pylo/auth-nextjs";

export const proxy = createPyloProxy({
  publicPaths: ["/auth"],
});

export const config = {
  matcher: [
    "/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
  ],
}
```

This protects every page and redirects unauthenticated users to `/auth/login`. Tokens refresh before
they expire.

The matcher is the
[negative match pattern](https://nextjs.org/docs/app/api-reference/file-conventions/proxy#negative-matching)
from the Next.js docs. Extend the exclusion list with any folder you serve assets from
(`|images|fonts`), otherwise a logged-out visitor is redirected to the login page instead of
receiving the file. API route handlers are excluded as well — check auth inside them with
[`requireAuth()`](/authentication/server-utilities).

> **Custom middleware**
> For custom redirect logic or route protection, see [Login &
> Logout](/authentication/login-and-logout#advanced-setup).

## Social login

Two route handlers add Google and Microsoft login. See
[Social Login](/authentication/social-login#nextjs).

## Next steps

- Add [Login & Logout](/authentication/login-and-logout) pages
- Use [Server Utilities](/authentication/server-utilities) for auth checks in Server Components
- Add the [Next.js SDK](/getting-started/quickstart-nextjs) for data access

Next: [Login & Logout](/authentication/login-and-logout)
