@imtf/auth
v3.0.0
Published
Better auth wrapper for imtf usage
Downloads
2,594
Readme
@imtf/auth - Better Auth wrapper
Thin wrapper around better-auth tailored for IMTF applications. Provides IMTF-specific auth configuration, hooks, and route helpers on top of better-auth, for use in Next.js apps.
Pre-requisites
The following peer dependencies must be installed:
better-auth1.7.1zod4.3.6 or higher — must stay version-matched withbetter-auth's ownzoddependency@mui/material7.1.0 or higher@mui/lab7.0.1-beta.18 or higherreactandreact-dom18.0.0 or 19.0.0 or higher
Installation
npm install @imtf/authUsage
This package supplies IMTF's better-auth configuration and a couple of OIDC-flow helpers — it does not wrap betterAuth()/createAuthClient() themselves. Call those directly with the options this package returns.
Server: auth.ts
import "server-only";
import { getBetterAuthOptions } from "@imtf/auth/server";
import { betterAuth, type BetterAuthOptions } from "better-auth";
export const auth = betterAuth({
...getBetterAuthOptions({
oidcDiscoveryUrl: `${process.env.OIDC_ISSUER_URL}/.well-known/openid-configuration`,
authSecret: process.env.AUTH_SECRET!,
authClientId: process.env.OIDC_CLIENT_ID!,
authClientSecret: process.env.OIDC_CLIENT_SECRET!,
authBaseURL: process.env.AUTH_BASE_URL,
}),
} satisfies BetterAuthOptions);Client: auth-client.ts
"use client";
import { createAuthClient } from "better-auth/react";
export const authClient = createAuthClient();Route handler: app/api/auth/[...all]/route.ts
import type { NextRequest } from "next/server";
import { auth } from "@/auth";
function handler(request: NextRequest) {
return auth.handler(request);
}
export const GET = handler;
export const POST = handler;Federated sign-out route: app/api/auth/sign-out-url/route.ts
import { getSignOutUrlRoute } from "@imtf/auth/server";
import { headers } from "next/headers";
import { auth } from "@/auth";
export const GET = getSignOutUrlRoute({
auth,
discoveryUrl: `${process.env.OIDC_ISSUER_URL}/.well-known/openid-configuration`,
headers,
clientId: process.env.OIDC_CLIENT_ID,
});
clientIdlets the route build an end-session URL even when no ID token is available — for example when the OIDC provider's callback failed before better-auth stored an account cookie (missing email claim, denied consent, etc.). Without it, that case has no way to end the provider's SSO session, which otherwise leaves the user stuck in a silent re-authentication loop.
Session check in a server component
import { headers } from "next/headers";
import { redirect } from "next/navigation";
import { auth } from "@/auth";
export async function AuthGuard({ children }: { children: React.ReactNode }) {
const { accessToken } = await auth.api
.getAccessToken({ body: { useAccountCookie: true }, headers: await headers() })
.catch(() => ({ accessToken: undefined }));
if (!accessToken) redirect("/auth/sign-in");
return children;
}Sign-in and sign-out (client components)
"use client";
import { PROVIDER_ID, useSignOut } from "@imtf/auth";
import { authClient } from "@/auth-client";
function SignInButton() {
const handleSignIn = () =>
void authClient.signIn.social({ provider: PROVIDER_ID, callbackURL: "/" });
return <button onClick={handleSignIn}>Sign in</button>;
}
function SignOutButton() {
const { handleSignOut } = useSignOut({ authClient });
return <button onClick={handleSignOut}>Sign out</button>;
}Full export list
The package has two entry points. @imtf/auth is safe to import from client components; @imtf/auth/server must only be imported from server code.
// Client-safe — no `better-auth` server code in the module graph.
import { getBetterAuthClientOptions, useSignOut, PROVIDER_ID } from "@imtf/auth";
// Server only — pulls in `better-auth/next-js`, `better-auth/plugins` and `next/headers`.
import { getBetterAuthOptions, getSignOutUrlRoute, PROVIDER_ID } from "@imtf/auth/server";
getBetterAuthClientOptionsis deprecated as ofbetter-auth1.7 — generic OAuth sign-in no longer needs a client plugin, socreateAuthClient()can be called with no options as shown above.
Development
Prior to development, make sure you have installed the dependencies from the repository root:
pnpm installTesting
To run the tests, just run:
pnpm run testCoverage report can be generated with:
pnpm run test:coverageMigration from v1 to v2
@imtf/auth v2 upgrades its better-auth peer dependency from 1.6.30 to 1.7.1. better-auth 1.7 rewrote the generic OAuth plugin as a first-class social provider — see the Better Auth 1.7 upgrade guide for the full list of breaking changes upstream. The changes relevant to consumers of this package are:
- OAuth callback URL path changed. The redirect URI that
better-authexposes for the generic OIDC provider moved from{baseURL}/oauth2/callback/{providerId}to{baseURL}/callback/{providerId}(e.g.https://app.example.com/api/auth/oauth2/callback/oidc-provider→https://app.example.com/api/auth/callback/oidc-provider). You must update the redirect URI registered with your OIDC provider/IdP client before deploying this upgrade, or sign-in will fail. getSignOutUrlRoutedropped itsproviderIdoption.better-auth'sgetAccessTokenAPI no longer acceptsproviderIdto select an account; it now resolves the account from the signed account cookie (useAccountCookie: true), matching this package's database-less,storeAccountCookie: trueconfiguration. If you were passingproviderIdtogetSignOutUrlRoute, remove it — it is no longer read.- Server helpers moved to
@imtf/auth/server.getBetterAuthOptionsandgetSignOutUrlRouteare no longer exported from the package root; update those two imports to@imtf/auth/server. The root entry now exposes only the client-safe surface (PROVIDER_ID,useSignOut,getBetterAuthClientOptions). Previously the single barrel re-exported both halves, so any client component importing even a constant from@imtf/authdraggedbetter-auth's server router into the browser bundle — including an unused OpenAPI reference page that loads a script fromcdn.jsdelivr.net, which reads as a remote-script inclusion to security scanners. - No client plugin is required for generic OAuth sign-in anymore.
getBetterAuthClientOptions()no longer registersgenericOAuthClient()(removed upstream). Generic/custom OAuth providers now sign in through the standardauthClient.signIn.social({ provider })/authClient.linkSocial({ provider })methods. No action needed on your end beyond upgrading — this package's exported options already reflect the change.
