> Login and logout flows and custom middleware with @pylo/auth-nextjs

# Login & Logout

## Server actions

Wrap the SDK's `login` and `logout` functions in server actions:

```typescript filename="app/auth/actions.ts"
'use server';

import { login, logout } from "@pylo/auth-nextjs";

export async function loginAction(formData: FormData) {
  const email = formData.get('email') as string;
  const password = formData.get('password') as string;
  return login(email, password);
}

export async function logoutAction() {
  return logout();
}
```

## Login page

```tsx filename="app/auth/login/page.tsx"
'use client';

import { useRouter } from "next/navigation";
import { loginAction } from "./actions";

export default function LoginPage() {
  const router = useRouter();

  async function handleSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);
    const result = await loginAction(formData);

    if (result.success) {
      router.push('/dashboard');
    } else {
      alert(result.error?.message || 'Login failed');
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      <input name="email" type="email" placeholder="Email" required />
      <input name="password" type="password" placeholder="Password" required />
      <button type="submit">Login</button>
    </form>
  );
}
```

## Logout button

```tsx filename="components/logout-button.tsx"
import { logoutAction } from "@/app/auth/actions";

export function LogoutButton() {
  return (
    <form action={logoutAction}>
      <button type="submit">Logout</button>
    </form>
  );
}
```

## Advanced setup

Use `pyloAuth()` instead of `createPyloProxy()` for full control over the auth flow:

```typescript filename="proxy.ts"
import { pyloAuth } from "@pylo/auth-nextjs";
import { NextRequest } from "next/server";

export async function proxy(request: NextRequest) {
  const { loggedIn, redirect, response } = await pyloAuth(request, {
    publicPaths: ["/auth"],
  });

  if (!loggedIn && !request.nextUrl.pathname.startsWith("/auth")) {
    const loginUrl = new URL("/auth/login", request.url);
    loginUrl.searchParams.set("redirect", request.nextUrl.pathname);
    return redirect(loginUrl);
  }

  return response;
}
```

Keep the `config.matcher` from [Next.js Setup](/authentication/nextjs-setup#middleware).

## AuthContext reference

`pyloAuth()` returns:

| Field            | Type                                   | Description                                                               |
| ---------------- | -------------------------------------- | ------------------------------------------------------------------------- |
| `user`           | `PyloUser \| null`                     | The authenticated user, or `null`                                         |
| `loggedIn`       | `boolean`                              | `true` if the user is authenticated                                       |
| `redirect`       | `(url: string \| URL) => NextResponse` | Redirects page requests, passes through for Server Actions and API routes |
| `response`       | `NextResponse`                         | The response to return, with updated cookies from token refresh           |
| `isServerAction` | `boolean`                              | `true` if the current request is a Server Action                          |
| `isApiRoute`     | `boolean`                              | `true` if the current request is an API route                             |

Next: [Server Utilities](/authentication/server-utilities)
