API Handlers
How to integrate Light-Auth with the routing mechanisms of SSR Frameworks.
API Handlers Overview
Light-Auth requires specific API routes to handle authentication flows, including OAuth redirects, callbacks, and session management. These routes are automatically generated by Light-Auth, but you need to expose them through your framework's routing system.
What API handlers do:
OAuth Authorization: Handle the initial redirect to the OAuth provider.
OAuth Callbacks: Process the response from the OAuth provider after authentication, and create the session and the user.
Session & User Management: Return the current session and user to your client components. These endpoints are read-only, and the OAuth tokens are never sent to the browser.
Token Refresh: Handle automatic refresh of access tokens.
Sign In / Out: Manage the login / logout processes.
Email & Password: Handle the login, the registration and the password reset of the credentials provider.
Protection: Check the CSRF tokens and the origin of the requests, and apply your rate limiter.
CreateLightAuth() function. You just need to expose them through your framework's routing system.import { CreateLightAuth } from "@light-auth/nextjs";
export const {
providers,
handlers, // <--------- API route handlers
signIn,
signOut,
getAuthSession,
getUser
} = CreateLightAuth({providers: [googleProvider]});Integration with SSR Frameworks
Once you have set up the API handlers, you need to integrate them with your SSR framework's routing system.
Here are some examples, depending on the framework you are using:
By default, Light-Auth expects the API handlers to be exposed at /api/auth/[...lightauth].
Once created, add the code to intercept requests:
import { handlers } from "@/lib/auth";
export const { GET, POST } = handlers;export const { GET, POST } = handlers; to properly expose the route handlers.This file exposes the Light-Auth handlers to handle all authentication-related requests.
The [...lightauth] catch-all route parameter allows Light-Auth to handle various authentication paths like /api/auth/login/google or /api/auth/callback/google.
Custom Base Path
The default base path for Light-Auth is /api/auth. This means that the API handlers are expected to be exposed at /[ROOT]/api/auth/[...lightauth]/route.ts.
You can customize the base path by providing the basePath option to the CreateLightAuth function:
import { CreateLightAuth } from "@light-auth/nextjs";
// Initialize Light-Auth with custom base path
export const allHandlers = CreateLightAuth({
providers: [googleProvider],
basePath: "/custom/auth", // <---------------- Custom base path
});With this custom base path, instead of creating your file at /[ROOT]/api/auth/[...lightauth]/route.ts, you need to create your route handler file at: /[ROOT]/custom/auth/[...lightauth]/route.ts
As an example, using NextJs if you set the base path to /custom/auth, you would create your route handler file at /app/custom/auth/[...lightauth]/route.ts:
import { handlers } from "@/lib/auth";
export const { GET, POST } = handlers;The base path can also be set with the LIGHT_AUTH_BASE_PATH environment variable. Give the same base path to your client functions, as the server environment variables are not available in the browser:
"use client";
import { CreateLightAuthClient } from "@light-auth/nextjs/client";
export const { getAuthSession, getUser, signIn, signOut } = CreateLightAuthClient({ basePath: "/custom/auth" });${LIGHT_AUTH_URL}/custom/auth/callback/google): when changing it, make sure to update the callback URLs in your OAuth provider configuration as well.[...lightauth]
The [...lightauth] catch-all-routes parameter is mandatory for Light-Auth to work correctly, but you can customize the name if needed.
For example, you can change it to [...auth],[...hdlers],[...something] or any other name that fits your routing structure.
Understanding the Route Structure
Light-Auth creates several endpoints under the base path to handle different aspects of the authentication flow:
Supposing you didn't set a custom base path (it's then /api/auth as default), the following routes are handled by Light-Auth:
| Route | Method | Purpose |
|---|---|---|
/api/auth/login/:providerName?callbackUrl=:callbackUrl&csrfToken=:csrfToken | GET | Initiates the OAuth flow by redirecting to the provider's authorization page.
|
/api/auth/logout?revokeToken=:boolean&callbackUrl=:callbackUrl&csrfToken=:csrfToken | GET | Handles the logout process and clears the session.
|
/api/auth/callback/:providerName | GET, POST | Handles the callback from the OAuth provider during OAuth authentication. Some providers (Apple) post their response ( You should not call this route directly. It is only meant to be used internally by Light-Auth. |
/api/auth/csrf | POST | Returns a new CSRF token. Called by the client functions before each sign in, sign out or credentials request. |
/api/auth/session | POST | Returns the current session information. Can be null if user is not authenticated. Renews the session expiration when needed. |
/api/auth/user/api/auth/user/:providerUserId | POST | Returns the user of the current session, without its OAuth tokens. Can be null if user is not authenticated. Requesting the user of another session returns a 403 error. |
/api/auth/credentials/login/api/auth/credentials/register/api/auth/credentials/reset-password/request/api/auth/credentials/reset-password/confirm | POST | Email & password endpoints of the credentials provider. See Email & Password. |
All these routes are handled by Light-Auth, and you don't need to call them directly: the client functions call them for you.
However, this is something you still can do, from a client-side component, for example:
const response = await fetch("/api/auth/session", { method: "POST" });
const session = await response.json();
console.log(session); // null if user is not authenticated otherwise { name: "John Doe", email: "john.doe@example.com", ... }setAuthSession() and setUser() server functions. The cross-origin requests are rejected, except on the OAuth callback.Recommendations
Recommendations for optimal routing integration
Use Consistent Base Paths
Keep your authentication routes under a consistent path structure to make your application easier to maintain.
Update Redirect URLs
When changing the base path, always update the redirect URLs in both your OAuth provider configuration and your Light-Auth setup.
Secure Your Routes
Consider adding additional security measures like rate limiting to your authentication routes to prevent abuse.
Test Your Routes
Always test your authentication routes thoroughly after setup to ensure they're working correctly.