Login & Logout
Server actions
Wrap the SDK's login and logout functions in server actions:
app/auth/actions.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
'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
app/auth/login/page.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
'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
components/logout-button.tsx
1
2
3
4
5
6
7
8
9
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:
proxy.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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;
}
export const config = {
matcher: [
"/((?!_next/static|_next/image|favicon.ico|.*\..*|$).*)",
"/",
],
}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 |