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:

1

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

2

OAuth Callbacks: Process the response from the OAuth provider after authentication, and create the session and the user.

3

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.

4

Token Refresh: Handle automatic refresh of access tokens.

5

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

6

Email & Password: Handle the login, the registration and the password reset of the credentials provider.

7

Protection: Check the CSRF tokens and the origin of the requests, and apply your rate limiter.

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/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:

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;

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:

/lib/auth-client.ts
"use client";

import { CreateLightAuthClient } from "@light-auth/nextjs/client";

export const { getAuthSession, getUser, signIn, signOut } = CreateLightAuthClient({ basePath: "/custom/auth" });
Important: The callback URLs depend on the base path (${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.

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=:callbackUrl&csrfToken=:csrfTokenGETInitiates the OAuth flow by redirecting to the provider's authorization page.
  • The providerName is the name of the OAuth provider (e.g., google, github). The provider factories define a default name, that you can override:
  • import { createGoogleProvider } from "@light-auth/core";
    
    const googleProvider = createGoogleProvider({
      providerName: "google", // <--- default value, you can change it to anything you want
      clientId: process.env.GOOGLE_CLIENT_ID!,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
    });
  • The callbackUrl is the URL to redirect to after successful authentication. It must be a path of your application.
  • The csrfToken is the CSRF token, sent back by the signIn client function.
/api/auth/logout?revokeToken=:boolean&callbackUrl=:callbackUrl&csrfToken=:csrfTokenGETHandles the logout process and clears the session.
  • The revokeToken parameter indicates whether to revoke the tokens at the OAuth provider.
  • The callbackUrl is the URL to redirect to after logout. It must be a path of your application.
  • The csrfToken is the CSRF token, sent back by the signOut client function.
/api/auth/callback/:providerNameGET, POST

Handles the callback from the OAuth provider during OAuth authentication. Some providers (Apple) post their response (form_post).

You should not call this route directly. It is only meant to be used internally by Light-Auth.
/api/auth/csrfPOSTReturns a new CSRF token. Called by the client functions before each sign in, sign out or credentials request.
/api/auth/sessionPOSTReturns 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
POSTReturns 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
POSTEmail & 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", ... }
Sessions and users can't be modified through these endpoints: use the 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.