Migration Guide

Upgrade your application from Light-Auth 0.3 to Light-Auth 0.4.

Overview

Light-Auth 0.4 no longer depends on Arctic: it ships its own OAuth 2.0 / OpenID Connect client, with ready-to-use providers. This release also hardens the security of the endpoints. Most applications only need to:

  1. replace their provider declarations,
  2. set the LIGHT_AUTH_URL environment variable,
  3. update the onSessionSaving / onUserSaving hooks reading the tokens.
npm install @light-auth/nextjs@latest @light-auth/core@latest
npm uninstall arctic

1. Replace the Arctic providers

Providers are now created with the factories exported by @light-auth/core. A provider still declared with an arctic property is rejected with an explicit error.

Before (0.3)
import { Google, MicrosoftEntraId } from "arctic";

const googleProvider = {
  providerName: "google",
  arctic: new Google(GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, "http://localhost:3000/api/auth/callback/google"),
  searchParams: new Map([["access_type", "offline"]]),
};

const microsoftProvider = {
  providerName: "microsoft",
  arctic: new MicrosoftEntraId(TENANT_ID, CLIENT_ID, CLIENT_SECRET, "http://localhost:3000/api/auth/callback/microsoft"),
  scopes: ["offline_access"],
};
After (0.4)
import { createGoogleProvider, createMicrosoftEntraIdProvider } from "@light-auth/core";

const googleProvider = createGoogleProvider({
  clientId: GOOGLE_CLIENT_ID,
  clientSecret: GOOGLE_CLIENT_SECRET,
  accessType: "offline",
});

const microsoftProvider = createMicrosoftEntraIdProvider({
  tenant: TENANT_ID,
  clientId: CLIENT_ID,
  clientSecret: CLIENT_SECRET,
  scopes: ["offline_access"],
});

The openid, profile and email scopes are added by the OpenID Connect factories. Other providers (GitHub, Discord, Apple, any OpenID Connect or OAuth 2.0 provider) are described in Providers.

2. Set the callback URL

The callback URL was given to the Arctic constructor. It is now computed from the LIGHT_AUTH_URL environment variable (${LIGHT_AUTH_URL}${basePath}/callback/${providerName}), or set with the redirectUri option of each provider:

LIGHT_AUTH_URL=http://localhost:3000

The resulting URLs (http://localhost:3000/api/auth/callback/google...) are the same as before when you kept the default base path and provider names.

3. Update the hooks reading the tokens

onSessionSaving, onUserSaving and the onGetOAuth2Tokens provider hook now receive a plain LightAuthTokens object instead of the Arctic OAuth2Tokens class. The id_token claims don't need to be decoded anymore: they are validated and available in idTokenClaims.

Before (0.3)
onSessionSaving: async (session, tokens) => {
  if (!tokens?.idToken()) return session;
  const idToken = JSON.parse(Buffer.from(tokens.idToken().split(".")[1], "base64").toString());
  if (typeof idToken.given_name === "string") session.firstName = idToken.given_name;
  return session;
},
After (0.4)
onSessionSaving: async (session, tokens) => {
  const claims = tokens?.idTokenClaims;
  if (typeof claims?.given_name === "string") session.firstName = claims.given_name;
  return session;
},
Arctic OAuth2Tokens (0.3)LightAuthTokens (0.4)
tokens.accessToken()tokens.accessToken
tokens.accessTokenExpiresAt()tokens.accessTokenExpiresAt
tokens.refreshToken()tokens.refreshToken
tokens.idToken()tokens.idToken (raw JWT) or tokens.idTokenClaims (validated claims)
tokens.scopes()tokens.scopes
tokens.tokenType()tokens.tokenType
tokens.datatokens.raw

4. Check the secret

LIGHT_AUTH_SECRET_VALUE must be at least 32 characters long: CreateLightAuth now throws at startup otherwise. The first 32 characters are used as before, so the existing sessions stay valid.

5. Write sessions and users from the server

CreateLightAuthClient() no longer returns setAuthSession and setUser (setSession / setUser with Nuxt), and the matching endpoints have been removed: a browser could save any value in its session. Update them from your server code instead, with the functions returned by CreateLightAuth(), in a Server Action for instance:

./app/actions/session.ts
"use server";

import { getAuthSession, setAuthSession } from "@/lib/auth";

export async function updateFirstName(firstName: string) {
  const session = await getAuthSession();
  if (!session) return null;

  // validate the values coming from the browser before saving them
  session.firstName = firstName.trim().slice(0, 50);
  return await setAuthSession(session);
}

6. Read the OAuth tokens on the server

The getUser() client function no longer returns accessToken, refreshToken and accessTokenExpiresAt, and the browser can only read the user of its own session. Call the APIs requiring the access token from your server code, where getUser() still returns the tokens (and refreshes them when needed).

Other changes

These changes don't require any update when you use the Light-Auth functions, but may impact custom code:

  • CSRF: the login and logout endpoints require the csrfToken query parameter, and the credentials endpoints the x-light-auth-csrf-token header. If you build these requests yourself, see Security.
  • Callback URLs are restricted to the paths of your application: a URL pointing to another domain is replaced by /.
  • Sessions are now renewed (sliding expiration) when less than half of their lifetime remains, and carry a standard exp claim.
  • Rate limiter: the client IP is read from the right-most X-Forwarded-For entry (the left-most ones can be spoofed), then from X-Real-IP, and the counters are kept per request path, query string excluded. A new keyGenerator option lets you use the IP given by your framework, and the response has a Retry-After header. See Rate Limit.
  • File user adapter: the files are now named after the base64url encoded user id. Existing files are still read, and renamed on the next save.
  • Refresh tokens revoked or expired at the provider (invalid_grant) are removed from the user, which has to sign in again to get new tokens.

New features

  • Built-in providers for Google, Microsoft Entra ID, GitHub, Discord, Apple, and any OpenID Connect or OAuth 2.0 provider: Providers.
  • Email & password authentication with the credentials provider: Email & Password.
  • Event hooks: onLogin, onLogout, onRegister, onSessionExpired, onTokenRefresh, onPasswordReset and onError: Events.
  • A sessionName option to choose the name of the session cookie.
  • Server functions (getAuthSession(), getUser()...) running in-process, without any HTTP round-trip.
Upgrade all the @light-auth/* packages together, so that your framework package and @light-auth/core share the same version.