> Server-side auth helpers, get the current user, check auth status, access tokens

# Server Utilities

Server-side helpers for Server Components, Server Actions, and Route Handlers.

## requireAuth

Get the authenticated user or redirect to login.

```tsx filename="app/dashboard/page.tsx"
import { requireAuth } from "@pylo/auth-nextjs";

export default async function DashboardPage() {
  const user = await requireAuth();
  // user exists here, or requireAuth already redirected
  return <p>Welcome, {user.email}</p>;
}
```

Redirects to `/auth/login` by default:

```typescript filename="example.ts"
const user = await requireAuth({ redirectTo: '/login' });
```

## getUser

The current user, or `null`.

```tsx filename="app/profile/page.tsx"
import { getUser } from "@pylo/auth-nextjs";

export default async function ProfilePage() {
  const user = await getUser();

  if (!user) {
    return <p>Not logged in</p>;
  }

  return <p>Email: {user.email}</p>;
}
```

## loggedIn

```tsx filename="app/page.tsx"
import { loggedIn } from "@pylo/auth-nextjs";

export default async function Page() {
  if (await loggedIn()) {
    return <AuthenticatedContent />;
  }
  return <PublicContent />;
}
```

## getAuthToken / getRefreshToken

The raw tokens from cookies, for custom API calls or debugging.

```typescript filename="example.ts"
import { getAuthToken, getRefreshToken } from "@pylo/auth-nextjs";

const authToken = await getAuthToken();       // string | undefined
const refreshToken = await getRefreshToken(); // string | undefined
```

## refreshTokens

Manual token refresh. The middleware already does this, so you need it only for custom flows.

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

const result = await refreshTokens();

if (result.success) {
  console.log(result.authToken);
} else {
  console.error(result.error?.message);
}
```

## Cookie configuration

Pylo stores tokens in HTTP-only cookies. Customize via `cookieOptions` on `createPyloProxy()` or
`pyloAuth()`:

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

export const proxy = createPyloProxy({
  publicPaths: ["/auth"],
  cookieOptions: {
    secure: true,           // HTTPS only (default: true in production)
    sameSite: "lax",        // CSRF protection (default: 'lax')
    domain: ".example.com", // cross-subdomain sharing
    path: "/",              // cookie path (default: '/')
    authMaxAge: 3600,       // auth token lifetime in seconds (default: 1 hour)
    refreshMaxAge: 604800,  // refresh token lifetime in seconds (default: 7 days)
  },
});
```

| Option          | Type                          | Default              | Description                               |
| --------------- | ----------------------------- | -------------------- | ----------------------------------------- |
| `secure`        | `boolean`                     | `true` in production | Only send cookies over HTTPS              |
| `sameSite`      | `"strict" \| "lax" \| "none"` | `"lax"`              | CSRF protection setting                   |
| `domain`        | `string`                      | `""`                 | Cookie domain for cross-subdomain sharing |
| `path`          | `string`                      | `"/"`                | Cookie path                               |
| `authMaxAge`    | `number`                      | `3600` (1 hour)      | Auth token cookie lifetime in seconds     |
| `refreshMaxAge` | `number`                      | `604800` (7 days)    | Refresh token cookie lifetime in seconds  |

Cookie names: `pylo_auth_token` (JWT auth token) and `pylo_refresh_token` (refresh token).

## Function reference

| Function            | Return type                    | Description                   |
| ------------------- | ------------------------------ | ----------------------------- |
| `requireAuth()`     | `Promise<PyloUser>`            | Get user or redirect to login |
| `getUser()`         | `Promise<PyloUser \| null>`    | Get user or null              |
| `loggedIn()`        | `Promise<boolean>`             | Check if authenticated        |
| `getAuthToken()`    | `Promise<string \| undefined>` | Auth token from cookies       |
| `getRefreshToken()` | `Promise<string \| undefined>` | Refresh token from cookies    |
| `refreshTokens()`   | `Promise<AuthResult>`          | Manually refresh tokens       |

Next: [API Tokens](/authentication/api-tokens)
