Skip to content

Auth Providers (createAuth)

WebJs ships createAuth(), a NextAuth-style auth surface with OAuth providers, credentials login, and JWT sessions. Reach for this page when you want providers and sessions handled for you, and no external auth library in the dependency tree.

It is not the only route. If you want to own the session format, the password hashing, and the route-protection rules yourself, build on the framework primitives instead, which is what Build Your Own Authentication covers and what the blog example does. Pick createAuth() for OAuth and a batteries-included setup, pick the primitives when you want full control of the session.

Setup

// lib/auth.server.ts: create once
import { createAuth, Credentials, Google, GitHub } from '@webjsdev/server';
import { db } from '#db/connection.server.ts';

export const { auth, signIn, signOut, handlers } = createAuth({
  providers: [
    Credentials({
      async authorize(credentials) {
        const user = await db.query.users.findFirst({
          where: { email: credentials.email }
        });
        if (!user || !verifyPassword(credentials.password, user.passwordHash)) {
          return null;
        }
        return { id: user.id, name: user.name, email: user.email };
      },
    }),
    Google(),  // reads AUTH_GOOGLE_ID, AUTH_GOOGLE_SECRET from env
    GitHub(),  // reads AUTH_GITHUB_ID, AUTH_GITHUB_SECRET from env
  ],
  secret: process.env.AUTH_SECRET,
});

Mount the auth API route

// app/api/auth/[...path]/route.ts
import { handlers } from '#lib/auth.server.ts';
export const GET = handlers.GET;
export const POST = handlers.POST;

Read the session

// In any page or server action:
import { auth } from '#lib/auth.server.ts';

export default async function Dashboard() {
  const session = await auth();
  if (!session) throw redirect('/login');
  return html`<h1>Welcome, ${session.user.name}</h1>`;
}

A redirect() thrown during a GET page render (an auth gate like this) defaults to 302 Found, the conventional bounce code. The same redirect() thrown from a form-bound server action answers 303 See Other, as in Next.js, so the browser follows with a GET and the action runs once; called over RPC from a component, it navigates the client router to the target. An explicit redirect(url, status) overrides the GET-gate default. To type session.user so session.user.name needs no cast, see Typing the auth() Session User.

Sign in and sign out

// modules/auth/actions/session.server.ts, bound as <form action=${logIn}>
'use server';
import { AuthError } from '@webjsdev/server';
import { signIn, signOut } from '#lib/auth.server.ts';

export async function logIn(formData: FormData) {
  try {
    await signIn('credentials', formData, { redirectTo: '/dashboard' });
  } catch (error) {
    if (error instanceof AuthError) return { success: false, error: 'Wrong email or password.' };
    throw error; // the success redirect
  }
}

export async function logInWithGoogle() {
  await signIn('google', undefined, { redirectTo: '/dashboard' });
}

export async function logOut() {
  await signOut({ redirectTo: '/' });
}

signIn and signOut work the way Auth.js v5's do in a Next.js server action. Inside a request they set or clear the session cookie on the response and throw a redirect, which a form-bound action answers with a 303, so the form works with JavaScript off. A credentials sign-in whose authorize returns null throws CredentialsSignin, a subclass of AuthError with type set to 'CredentialsSignin'. Catch it to return a message, which re-renders the page with it on actionData. Left uncaught, it redirects to pages.error (or pages.signIn) with ?error=CredentialsSignin, as the /api/auth/signin/credentials route does. Pass { redirect: false } to get the target url back instead of the redirect. Called with no request in scope, from a script, they return the Response the auth routes send.

signOut is also reachable as a route: the mounted handlers serve POST /api/auth/signout, so a plain <form method="POST" action="/api/auth/signout"> logs a user out with no JavaScript. That is how the auth demo in the WebJs gallery renders its logout button. A GET /api/auth/signout never signs out, as in Auth.js: it answers a page whose button posts (or redirects to pages.signOut), because a link prefetch or a crawler following a GET would otherwise log the visitor out. The auth POST routes also refuse a cross-site request, the same origin check server actions get, with webjs.allowedOrigins honoured.

Protect routes with middleware

As in Auth.js, auth is also middleware. Export it from the root middleware.ts and decide who passes in callbacks.authorized: true continues, false redirects to pages.signIn (or /api/auth/signin) with a callbackUrl, and a returned Response is sent as is. Without the callback the middleware only attaches the session as req.auth.

// middleware.ts
export { auth as middleware } from '#lib/auth.server.ts';

// lib/auth.server.ts
createAuth({
  // ...providers
  pages: { signIn: '/login' },
  callbacks: {
    authorized: ({ auth, request }) =>
      !!auth || !new URL(request.url).pathname.startsWith('/dashboard'),
  },
});

To run your own logic, wrap it: export default auth((req) => ...) gives the function req.auth, and returning nothing continues to the page.

Return to the page the user started from

Pass redirectTo and the user lands there after signing in, for OAuth providers as well as credentials. A plain form is enough: the mounted handler reads the field, carries it through the provider round trip in a short-lived signed cookie, and the callback lands on it.

<form method="POST" action="/api/auth/signin/github">
  <input type="hidden" name="redirectTo" value="/dashboard/x">
  <button>Sign in with GitHub</button>
</form>

A link works too (/api/auth/signin/github?redirectTo=/dashboard/x), and so does signIn('github', undefined, { redirectTo }) from an action. A redirectTo that comes from a request must be a same-origin local path: one leading /, not followed by / or . An absolute URL or a protocol-relative //host is dropped rather than repaired, and the sign-in lands on /, so the field can never be used as an open redirect. Every target, whether your server code passed it to signIn() / signOut(), a form submitted it, or the signIn callback returned it, goes through Auth.js's callbacks.redirect({ url, baseUrl }). Its default keeps a local path or a URL on this origin (as its path, which must itself be a local path) and sends anything else to /; a signIn callback's URL it drops denies the sign-in. To land on another origin, an identity provider's end-session URL for instance, return it from the callback: redirect: ({ url, baseUrl }) => url.startsWith('https://idp.example/') ? url : new URL(url, baseUrl).pathname. A denied sign-in still goes to pages.error.

As in Auth.js, a server-side signIn() or signOut() with no redirectTo returns to the page it was called from (the Referer, same-origin only), else /. From a sign-in form that is the sign-in page itself, so pass redirectTo to land elsewhere. The routes also read Auth.js's field name, callbackUrl, and a sign-out lands on redirectTo or /; pages.signOut is the sign-out page a GET /api/auth/signout shows, not where it lands.

Showing a failed sign-in

A failed credentials sign-in redirects to ${pages.error}?error=CredentialsSignin, falling back to the home page when pages.error is unset (which silently swallows the failure). Point the error page at your login route, then read the code and render a message:

createAuth({
  // ...providers, secret
  pages: { error: '/login' },  // a failed sign-in returns here
});

// app/login/page.ts
export default function LoginPage({ searchParams }) {
  const failed = searchParams.error === 'CredentialsSignin';
  return html`
    ${failed ? html`<p role="alert">Invalid email or password.</p>` : ''}
    <form method="POST" action="/api/auth/signin/credentials">...</form>
  `;
}

The auth demo in the WebJs gallery wires exactly this, so a wrong password shows a message on the login page instead of bouncing to the landing page with no feedback.

Callbacks

Customize the session and JWT with callbacks:

createAuth({
  // ...providers
  callbacks: {
    async jwt({ token, user }) {
      // Add custom fields to the JWT
      if (user) {
        token.sub = user.id;
        token.role = user.role;
      }
      return token;
    },
    async session({ session, token }) {
      // Expose custom fields to auth()
      session.user.id = token.sub;
      session.user.role = token.role;
      return session;
    },
  },
});

At sign-in the jwt callback receives what Auth.js passes it: { token, user, account, profile, trigger: 'signIn' }, where an OAuth account is the provider's token response (access_token, refresh_token, expires_at), so if (account) token.accessToken = account.access_token keeps it for later reads. A credentials authorize(credentials, request) gets the request too, and the session auth() returns carries expires.

The signIn callback follows Auth.js's rule: return true to allow, a url string to send the visitor there without signing them in, and anything else (including nothing) to deny with AccessDenied.

Type the session

By default auth() resolves { user: Record<string, unknown> }, so reading a custom field your callbacks set (like session.user.id) needs a cast and a typo slips past TypeScript. Opt into a typed user one of two ways.

Augment AuthUser (NextAuth/Auth.js style) to type every auth() call across the app. Declare the fields your session/jwt callbacks set:

// lib/auth.server.ts (or any .d.ts in the project)
declare module '@webjsdev/server' {
  interface AuthUser {
    id: string;
    role: 'admin' | 'member';
  }
}

Now session.user.id is string everywhere, and a misspelling like session.user.idd is a compile error.

Or parameterise the factory with createAuth<TUser>() to type just this instance, without a global augmentation:

interface AppUser {
  id: string;
  role: 'admin' | 'member';
}

export const { auth, signIn, signOut, handlers } =
  createAuth<AppUser>({ /* ...providers, secret */ });

const session = await auth();
session?.user.role; // typed as 'admin' | 'member', no cast

Both are types-only and opt-in: leave them out and auth().user stays the loose Record<string, unknown>, so existing code keeps working unchanged. The fields you declare should match what your callbacks actually write onto session.user.

Providers

ProviderEnv varsFlow
Credentials()NoneCustom authorize function, you handle password verification
Google()AUTH_GOOGLE_ID, AUTH_GOOGLE_SECRETOAuth 2.0 redirect flow
GitHub()AUTH_GITHUB_ID, AUTH_GITHUB_SECRETOAuth 2.0 redirect flow

As in Auth.js, an OAuth provider can be listed uncalled, providers: [GitHub], when its credentials come from the environment variables above.

Session strategies

JWT (default): Session data encrypted in a cookie, exactly as Auth.js encrypts it (a JWE, dir + A256CBC-HS512, the key derived from the secret and the cookie name), so the browser holding it cannot read what is inside. Stateless and scales horizontally without Redis. Cannot be revoked before expiry.

Database with an Auth.js adapter: pass one, as in Auth.js (adapter: DrizzleAdapter(db) from @auth/drizzle-adapter, or any @auth/*-adapter), and sessions become database rows: the strategy defaults to database, the cookie holds the session token, an OAuth sign-in creates the user and links the account (an email another user already has is refused with OAuthAccountNotLinked unless the provider sets allowDangerousEmailAccountLinking), a session is extended once session.updateAge has passed, and sign-out deletes it. A credentials sign-in gets a database session too, so it can be revoked (Auth.js needs strategy: 'jwt' there).

Database: Session ID in cookie, data in cache store. Can revoke sessions instantly. Requires Redis or similar for horizontal scaling.

createAuth({
  session: { strategy: 'database' },  // default: 'jwt'
  // ...
});

Cookie names

Over http the session cookie is webjs.auth, and the OAuth round trip uses webjs.auth.state and webjs.auth.redirect. Over https each name carries the __Host- prefix and the Secure flag: __Host-webjs.auth, __Host-webjs.auth.state, __Host-webjs.auth.redirect. That is Auth.js's rule: useSecureCookies when you set it, else whether the auth URL is https, AUTH_URL's when set, else the request's (behind a TLS-terminating proxy that forwards X-Forwarded-Proto, the request is https). NODE_ENV plays no part, so npm start over plain http still signs in. A browser stores a __Host- cookie only when it is Secure, has Path=/ and has no Domain, so an app on a sibling subdomain of a shared hosting domain cannot plant its own session cookie in yours and sign a visitor in to the wrong account. Over https only the prefixed names are read, so an app upgrading from an earlier version signs its users in once more. A test or tool that sets the cookie by hand for an https request uses the prefixed name.

Differences from Auth.js

Environment variables

AUTH_SECRET=your-random-secret-32-chars-minimum
AUTH_GOOGLE_ID=your-google-oauth-client-id
AUTH_GOOGLE_SECRET=your-google-oauth-client-secret
AUTH_GITHUB_ID=your-github-oauth-client-id
AUTH_GITHUB_SECRET=your-github-oauth-client-secret
AUTH_URL=https://app.example.com/api/auth   # optional, behind a proxy

As in Auth.js, AUTH_URL (or NEXTAUTH_URL) sets the public origin OAuth callback URLs use, so a provider gets a callback on your real domain when the app runs behind a proxy, and its path is the base path the routes are mounted at. Without it the request's origin and /api/auth are used. basePath in createAuth sets the mount point directly.

Generate a secret: node -e "console.log(require('crypto').randomBytes(32).toString('hex'))". webjs create writes one into .env for you. As in Auth.js, createAuth reads AUTH_SECRET itself when secret is left out, and secret: process.env.AUTH_SECRET type-checks as is. In development and tests (webjs dev, webjs test, or NODE_ENV=development / test) a missing secret is generated once into the gitignored .webjs/dev-secret with a warning, since a fresh clone has no .env. Anywhere else it is required, including a process with no NODE_ENV at all, and createAuth throws without one.