API Handlers
How to integrate Ligh-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.
Session & User Management: Create and validate session / user payloads, and save in cookies / datastore.
Token Refresh: Handle automatic refresh of access tokens.
Sign In / Out: Manage the login / logout processes.
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/signin/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;
[...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 | GET | Initiates the OAuth flow by redirecting to the provider's authorization page.
|
/api/auth/logout?revokeToken=:boolean&callbackUrl=:callbackUrl | GET | Handles the logout process and clears the session.
|
/api/auth/callback/:provider | GET | Handles the callback from the OAuth provider during OAuth authentication. You should not call this route directly. It is only meant to be used internally by Light-Auth. |
/api/auth/session | GET | Returns the current session information. Can be null if user is not authenticated. |
/api/auth/user | GET | Returns the current user information. Can be null if user is not authenticated or no UserAdapter has been configured. |
All these routes are handled by Ligth-Auth, and you don't need to call them directly.
However, this is something you still cand do, from a client-side component, for example:
const response = await fetch('/api/auth/session');
const data = await response.json();
console.log(data); // undefined if user is not authenticated otherwise { name: "John Doe", email: "john.doe@example.com" , ...}
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.