Open Serverless Auth Toolkit for Next.js
This package, `open-serverless-auth` (current version 0.2.0), provides a toolkit for integrating Next.js applications with a centralized Open Serverless Auth hub. It includes an Edge Middleware for protecting downstream applications by redirecting unauthorized users, and Server Action/Component helpers like `getUserData()` to retrieve authenticated user information. Its primary differentiator is simplifying centralized authentication architecture across subdomains using cross-subdomain cookies, abstracting away complex login UI development on client apps. It's designed to work seamlessly with Next.js App Router and assumes a peer dependency on `next` version 13 or higher. The current version suggests it's relatively new, likely in active development with potentially frequent updates, although a specific release cadence isn't stated. The core value proposition is enabling easy setup of a centralized authentication system, offloading authentication concerns from individual client applications.
Common errors
-
Error: `createAuthMiddleware` must be called with an object containing `domain` or `NEXT_PUBLIC_DOMAIN` environment variable must be set.
cause The Edge Middleware cannot determine the central authentication hub's domain, which is essential for redirecting unauthenticated users and managing cross-subdomain cookies.fixSet `process.env.NEXT_PUBLIC_DOMAIN` to the full domain of your auth hub (e.g., `auth.yourdomain.com`) in your Next.js application's environment variables, or explicitly pass the `domain` option to `createAuthMiddleware({ domain: 'auth.yourdomain.com' })`. -
TypeError: Cannot read properties of null (reading 'email') OR ReferenceError: user is not defined
cause The `user` object returned by `getUserData()` is `null` (indicating an unauthenticated state or an error during retrieval), and your code attempts to access its properties without a null check.fixAlways implement a null check for the `user` object and handle the unauthenticated state, typically by redirecting the user to a login page or an unauthorized page, e.g., `if (!user) { redirect('/unauthorized'); }`. -
TypeError: (0 , open_serverless_auth__WEBPACK_IMPORTED_MODULE_0__.createAuthMiddleware) is not a function
cause This error often indicates a CommonJS (CJS) vs. ESM import mismatch in an environment that expects ESM, such as the Next.js Edge Runtime for middleware. It can also occur if the bundle is corrupted or tree-shaking removed the function.fixEnsure you are using `import { createAuthMiddleware } from 'open-serverless-auth';` and not `require()`. Verify that your `middleware.ts` file is correctly configured as an ESM module if not already default.
Warnings
- gotcha Using the `devBypassUser` option in `createAuthMiddleware` allows unauthenticated access and injects a dummy user. While the library implements checks to automatically ignore this configuration when `process.env.NODE_ENV === 'production'`, developers should be aware of its security implications and never attempt to override these protections in live environments.
- gotcha This package is designed exclusively for Next.js 13+ applications utilizing the App Router. It leverages Next.js Edge Runtime for middleware and Server Components for `getUserData()`, making it incompatible with the Pages Router or older Next.js versions.
- gotcha The `matcher` configuration in `middleware.ts` is critical for defining which routes are protected. An improperly configured `matcher` can either leave sensitive routes unprotected or block legitimate access to static assets, API routes, or other Next.js internal paths.
Install
-
npm install open-serverless-auth -
yarn add open-serverless-auth -
pnpm add open-serverless-auth
Imports
- createAuthMiddleware
const { createAuthMiddleware } = require('open-serverless-auth');import { createAuthMiddleware } from 'open-serverless-auth'; - getUserData
const { getUserData } = require('open-serverless-auth');import { getUserData } from 'open-serverless-auth';
Quickstart
import { createAuthMiddleware, getUserData } from 'open-serverless-auth';
import { redirect } from 'next/navigation';
// --- src/middleware.ts ---
export const middleware = createAuthMiddleware({
// The domain of your central auth hub, e.g., 'auth.yourdomain.com'
// Falls back to process.env.NEXT_PUBLIC_DOMAIN if not provided.
// domain: process.env.NEXT_PUBLIC_DOMAIN,
// For local development only: Bypasses auth and injects a dummy user.
// This is automatically ignored in production environments.
devBypassUser: {
id: "local-dev-id",
email: "developer@example.com",
role: "ADMIN",
rules: { customPermission: true }
}
});
export const config = {
// Protect all routes except API routes, static assets, and favicon.ico
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};
// --- src/app/dashboard/page.tsx (Server Component) ---
export default async function DashboardPage() {
const user = await getUserData();
if (!user) {
// Redirect unauthenticated users to a login page or an unauthorized page
redirect('/unauthorized');
}
return (
<div>
<h1>Welcome back, {user.email}!</h1>
<p>Your role: {user.role}</p>
<p>Permissions: {JSON.stringify(user.rules)}</p>
</div>
);
}