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:

1

OAuth Authorization: Handle the initial redirect to the OAuth provider.

2

OAuth Callbacks: Process the response from the OAuth provider after authentication.

3

Session & User Management: Create and validate session / user payloads, and save in cookies / datastore.

4

Token Refresh: Handle automatic refresh of access tokens.

5

Sign In / Out: Manage the login / logout processes.

The API handlers are automatically generated by Light-Auth when you call the CreateLightAuth() function. You just need to expose them through your framework's routing system.
./src/app/auth.ts
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:

/app/api/auth/[...lightauth]/route.ts
import { handlers } from "@/lib/auth";

export const { GET, POST } = handlers;
Make sure to use the correct destructuring syntax 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:

app/lib/auth.ts
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:

/app/custom/auth/[...lightauth]/route.ts
import { handlers } from "@/lib/auth";
export const { GET, POST } = handlers;
Important: When changing the base path, 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.

This notion of a catch-all route parameter is specific to the framework you are using. It does not exist in express, for example.

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:

RouteMethodPurpose
/api/auth/login/:providerName?callbackUrl=:callbackUrlGETInitiates the OAuth flow by redirecting to the provider's authorization page.
  • The providerName is the name of the OAuth provider (e.g., google, github), you defined when creating the provider.
    It's arbitrary and can be anything you want:
  • import { googleProvider } from "@light-auth/nextjs";
    const googleProvider: LightAuthProvider = {
      providerName: "google", // <--- This is the provider name, you can change it to anything you want
      arctic: new Google(...),
    };                      
                          
  • The callbackUrl is the URL to redirect to after successful authentication. It can be a relative or absolute URL.
/api/auth/logout?revokeToken=:boolean&callbackUrl=:callbackUrlGETHandles the logout process and clears the session.
  • The revokeToken parameter indicates whether to revoke the access token from the OAuth provider.
  • The callbackUrl is the URL to redirect to after logout. It can be a relative or absolute URL.
/api/auth/callback/:providerGET

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/sessionGETReturns the current session information. Can be null if user is not authenticated.
/api/auth/userGETReturns 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.