@auth0/auth0-server-js

中文文档
1.17.0发布于 2026/10/23MITTypeScriptESM + CJS构建来源已验证近 30 天下载 22.9万

Auth0 Authentication SDK for Server-Side Applications on JavaScript runtimes

原始使用文档
文档目录15 节
  1. Documentation
  2. Getting Started
  3. 1. Install the SDK
  4. 2. Create the Auth0 SDK client
  5. 3. Configuring the Store
  6. 4. Add login to your Application (interactive)
  7. 5. Add logout to your application
  8. 6. Database Connections (Sign-up & Change Password)
  9. 7. Anonymous Sessions
  10. 8. Passkeys
  11. Feedback
  12. Contributing
  13. Raise an issue
  14. Vulnerability Reporting
  15. What is Auth0?

The @auth0/auth0-server-js library allows for implementing user authentication in web applications on a JavaScript runtime.

Using this SDK as-is in your application may not be trivial, as it is designed to be used as a building block for building framework-specific authentication SDKs.

Release Downloads License

📚 Documentation - 🚀 Getting Started - 💬 Feedback

Documentation

  • Examples - examples for your different use cases.
  • Docs Site - explore our docs site and learn more about Auth0.

Getting Started

1. Install the SDK

npm i @auth0/auth0-server-js

This library requires Node.js 20 LTS and newer LTS versions.

2. Create the Auth0 SDK client

Create an instance of the ServerClient. This instance will be imported and used anywhere we need access to the authentication methods.

import { ServerClient } from '@auth0/auth0-server-js';

const auth0 = new ServerClient<StoreOptions>({
  domain: '<AUTH0_DOMAIN>',
  clientId: '<AUTH0_CLIENT_ID>',
  clientSecret: '<AUTH0_CLIENT_SECRET>',
  authorizationParams: {
    redirect_uri: '<AUTH0_REDIRECT_URI>',
  },
});

The AUTH0_DOMAIN, AUTH0_CLIENT_ID, and AUTH0_CLIENT_SECRET can be obtained from the Auth0 Dashboard once you've created an application. This application must be a Regular Web Application. The AUTH0_REDIRECT_URI is needed to tell Auth0 what URL to redirect back to after successful authentication, e.g. http://localhost:3000/auth/callback. Your application needs to handle this endpoint and call the SDK's completeInteractiveLogin(url: string) to finish the authentication process. See below for more information.

3. Configuring the Store

The auth0-server-js SDK comes with a built-in store for both transaction and state data, however it's required to provide it a CookieHandler implementation that fits your use-case. The goal of auth0-server-js is to provide a flexible API that allows you to use any storage mechanism you prefer, but is mostly designed to work with cookie and session-based storage kept in mind.

The SDK methods accept an optional storeOptions object that can be used to pass additional options to the storage methods, such as Request / Response objects, allowing to control cookies in the storage layer.

For Web Applications, this may come down to a Stateless or Statefull session storage system.

Stateless Store

In a stateless storage solution, the entire session data is stored in the cookie. This is the simplest form of storage, but it has some limitations, such as the maximum size of a cookie.

The implementation may vary depending on the framework of choice, here is an example using Fastify:

import { FastifyReply, FastifyRequest } from 'fastify';
import { CookieSerializeOptions } from '@fastify/cookie';
import { 
  AbstractStateStore,
  AbstractTransactionStore,
  ServerClient,
  StateData,
  TransactionData
} from '@auth0/auth0-server-js';

export interface StoreOptions {
  request: FastifyRequest;
  reply: FastifyReply;
}

export class FastifyCookieHandler implements CookieHandler<StoreOptions> {
  setCookie(
    name: string,
    value: string,
    options?: CookieSerializeOptions,
    storeOptions?: StoreOptions
  ): void {
    // Handle storeOptions being undefined if needed.
    storeOptions!.reply.setCookie(name, value, options || {});
  }

  getCookie(name: string, storeOptions?: StoreOptions): string | undefined {
    // Handle storeOptions being undefined if needed.
    return storeOptions!.request.cookies?.[name];
  }

  getCookies(storeOptions?: StoreOptions): Record<string, string> {
    // Handle storeOptions being undefined if needed.
    return storeOptions!.request.cookies as Record<string, string>;
  }

  deleteCookie(name: string, storeOptions?: StoreOptions): void {
    // Handle storeOptions being undefined if needed.
    storeOptions!.reply.clearCookie(name);
  }
}

const auth0 = new ServerClient<StoreOptions>({
  transactionStore: new CookieTransactionStore({ secret: options.secret }, new FastifyCookieHandler()),
  stateStore: new StatelessStateStore({ secret: options.secret }, new FastifyCookieHandler()),
});

Stateful Store

In stateful storage, the session data is stored in a server-side storage mechanism, such as a database. This allows for more flexibility in the size of the session data, but requires additional infrastructure to manage the storage. The session is identified by a unique identifier that is stored in the cookie, which the storage would read in order to retrieve the session data from the server-side storage.

The implementation may vary depending on the framework of choice, here is an example using Fastify:

import type { FastifyReply, FastifyRequest } from "fastify";
import { CookieSerializeOptions } from '@fastify/cookie';
import { 
  AbstractStateStore,
  LogoutTokenClaims,
  ServerClient,
  StateData,
} from '@auth0/auth0-server-js';

export interface StoreOptions {
  request: FastifyRequest;
  reply: FastifyReply;
}

export class FastifyCookieHandler implements CookieHandler<StoreOptions> {
  setCookie(
    name: string,
    value: string,
    options?: CookieSerializeOptions,
    storeOptions?: StoreOptions,
  ): void {
    // Handle storeOptions being undefined if needed.
    storeOptions!.reply.setCookie(name, value, options || {});
  }

  getCookie(name: string, storeOptions?: StoreOptions): string | undefined {
    // Handle storeOptions being undefined if needed.
    return storeOptions!.request.cookies?.[name];
  }

  getCookies(storeOptions?: StoreOptions): Record<string, string> {
    // Handle storeOptions being undefined if needed.
    return storeOptions!.request.cookies as Record<string, string>;
  }

  deleteCookie(name: string, storeOptions?: StoreOptions): void {
    // Handle storeOptions being undefined if needed.
    storeOptions!.reply.clearCookie(name);
  }
}

const auth0 = new ServerClient<StoreOptions>({
  transactionStore: new CookieTransactionStore({ secret: options.secret }, new FastifyCookieHandler()),
  stateStore: new StatefulStateStore({ secret: options.secret }, new FastifyCookieHandler()),
});

Note that storeOptions is optional in the SDK's methods, but required when wanting to interact with the framework to set cookies. Here's how to pass the storeOptions to startInteractiveLogin() in a Fastify application:

fastify.get('/auth/login', async (request, reply) => {
  const storeOptions = { request, reply };
  const authorizationUrl = await auth0Client.startInteractiveLogin({}, storeOptions);

  reply.redirect(authorizationUrl.href);
});

Because storage systems in Web Applications are mostly cookie-based, the storeOptions object is used to pass the request and reply (in the case of Fastify, as per the example) objects to the storage methods, allowing to control cookies in the storage layer. It's expected to pass this to every interaction with the SDK.

4. Add login to your Application (interactive)

Before using redirect-based login, ensure the authorizationParams.redirect_uri is configured when initializing the SDK:

const auth0 = new ServerClient<StoreOptions>({
  // ...
  authorizationParams: {
    redirect_uri: '<AUTH0_REDIRECT_URI>',
  },
  // ...
});

The redirect_uri must be an absolute URL.

If you need to compute an absolute redirect URI per request (for example, in multi-domain deployments), pass authorizationParams.redirect_uri to startInteractiveLogin to override the configured default.

[!IMPORTANT]
You will need to register the AUTH0_REDIRECT_URI in your Auth0 Application as an Allowed Callback URLs via the Auth0 Dashboard:

In order to add login to any application, call startInteractiveLogin(), and redirect the user to the returned URL.

The implementation will vary based on the framework being used, but here is an example of what this would look like in Fastify:

fastify.get('/auth/login', async (request, reply) => {
  const authorizationUrl = await auth0Client.startInteractiveLogin({
    // The redirect_uri can also be configured here.
    authorizationParams: {
      redirect_uri: '<AUTH0_REDIRECT_URI>',
    },
  }, { request, reply });

  reply.redirect(authorizationUrl.href);
});

Once the user has succesfully authenticated, Auth0 will redirect the user back to the provided authorizationParams.redirect_uri which needs to be handled in the application. The implementation will vary based on the framework used, but what needs to happen is:

  • register an endpoint that will handle the configured authorizationParams.redirect_uri.
  • call the SDK's completeInteractiveLogin(url), passing it the full URL, including query parameters.

Here is an example of what this would look like in Fastify, with authorizationParams.redirect_uri configured as http://localhost:3000/auth/callback:

fastify.get('/auth/callback', async (request, reply) => {
  await auth0Client.completeInteractiveLogin(new URL(request.url, options.appBaseUrl), { request, reply });

  reply.redirect('/');
});

5. Add logout to your application

In order to log the user out of your application, as well as from Auth0, you can call the SDK's logout() method, and redirect the user to the returned URL.

fastify.get('/auth/logout', async (request, reply) => {
  const logoutUrl = await auth0Client.logout({ returnTo: '<RETURN_TO>' }, { request, reply });

  reply.redirect(logoutUrl.href);
});

[!IMPORTANT]
You will need to register the RETURN_TO in your Auth0 Application as an Allowed Logout URLs via the Auth0 Dashboard:

6. Database Connections (Sign-up & Change Password)

The ServerClient exposes a database sub-client with signUp and changePassword for self-service registration and password-reset requests against an Auth0 database connection. These are pure passthrough operations to the underlying Authentication API — they do not read or write the session/state store, so no store options are required for the operation itself.

import { ServerClient, SignUpError, ChangePasswordError } from '@auth0/auth0-server-js';

// Register a new user
try {
  const user = await auth0Client.database.signUp({
    email: '[email protected]',
    password: 'a-Str0ng-Password!',
    connection: 'Username-Password-Authentication',
    // Optional profile fields: username, givenName, familyName, name, nickname, picture, userMetadata
  });
  console.log(user.id); // normalized identifier; may be undefined if the server omits one
} catch (error) {
  if (error instanceof SignUpError) {
    console.error(error.code, error.message, error.cause);
  }
}

// Request a password-change email
try {
  const message = await auth0Client.database.changePassword({
    email: '[email protected]', // or `username: 'jane'` for username-only connections
    connection: 'Username-Password-Authentication',
    // Optional: organization
  });
  console.log(message); // plain-text confirmation from the server
} catch (error) {
  if (error instanceof ChangePasswordError) {
    console.error(error.code, error.message);
  }
}

[!IMPORTANT] These call the public /dbconnections/* endpoints, which send only clientId (never a client secret). changePassword resolves to a plain-text confirmation string. Neither method reads or writes the session/state store, so you can call them outside an authenticated request context. Domain selection is separate from session state: in static mode the constructor-configured domain is used, and in resolver (multi-tenant) mode the domain resolver still runs per call — pass storeOptions so it can select the intended tenant.

For full options and error handling, see the auth0-auth-js Database Connections examples (the underlying database client is identical) and the runnable examples/database-conns sample.

7. Anonymous Sessions

The ServerClient exposes an anonymous sub-client that gives a visitor an identity, and an access token for your API, before they log in. Configure an anonymousStore to switch it on:

import { StatelessAnonymousStore, ServerClient } from '@auth0/auth0-server-js';

const auth0 = new ServerClient<StoreOptions>({
  // ...
  anonymousStore: new StatelessAnonymousStore({ secret: options.secret }, new FastifyCookieHandler()),
});

// Give the visitor an anonymous identity and a token for your API.
const tokenSet = await auth0.anonymous.createSession(
  { audience: '<AUTH0_AUDIENCE>', metadata: { campaign: 'summer-sale' } },
  { request, reply }
);

// Later requests reuse the cached token, or mint a new one when it expired.
const { accessToken } = await auth0.anonymous.getAccessToken({ audience: '<AUTH0_AUDIENCE>' }, { request, reply });

The anonymous session is kept in its own store, so getSession() and getUser() keep returning undefined until the visitor really logs in.

Call createSession() only once auth0.anonymous.getSession() shows the visitor has no session yet. getAccessToken() serves cached tokens and only calls Auth0 when there is no cached token for the requested audience and scope, or when the cached one has expired.

Logging in and logging out both end the anonymous session for you. Every login method drops it once the user session is written, and auth0.logout() clears it as well. Read auth0.anonymous.getSession() before you complete the login when you need the anonymous sub to merge data into the user's account, or set clearAnonymousSessionOnLogin: false to keep the session and clear it yourself.

[!NOTE] Anonymous Sessions are in Early Access and have to be enabled on your tenant.

[!NOTE] startInteractiveLogin() automatically links an active anonymous session to the user at login via a Session Transfer Ticket. For login methods that do not go through /authorize (passkey.complete(), passkey.getToken(), completePasswordless(), loginBackchannel(), and similar), the link is unavailable — do the merge in your own application with the anonymous sub.

For the full API, the store options, the clearing behaviour and the details on linking an anonymous session to the user created at login, see the Anonymous Sessions section in EXAMPLES.md.

8. Passkeys

The ServerClient exposes a passkey sub-client to sign up and log in users with passkeys (WebAuthn). A passkey flow takes two requests: one that starts it, and one that completes it with the credential from the browser. In between, the SDK keeps the flow, including the Auth0 authSession, in the Transaction Store.

// Start a signup, or a login with `auth0.passkey.startLogin()`, and return the result to the browser.
const { authnParamsPublicKey, verificationRequired } = await auth0.passkey.startSignup(
  { email: '[email protected]' },
  { request, reply }
);

// The browser passes `authnParamsPublicKey` to `navigator.credentials.create()` (`navigator.credentials.get()`
// for a login) and sends the serialized credential back, together with the one-time codes Auth0 sent to the
// identifiers in `verificationRequired`, if any. Exchange the credential for tokens and create the session:
await auth0.passkey.complete({ credential, verification }, { request, reply });

The lower-level passkey.register(), passkey.challenge() and passkey.getToken() keep no flow state and leave the authSession to your application. Use them only when you need to keep the flow yourself.

For the dashboard setup, identifier verification, error handling and how the two sets of methods differ, see the Passkeys section in EXAMPLES.md.

Feedback

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please read the following:

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

Vulnerability Reporting

Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

What is Auth0?

Auth0 Logo

Auth0 is an easy to implement, adaptable authentication and authorization platform. To learn more checkout Why Auth0?

This project is licensed under the MIT license. See the LICENSE file for more info.

版本与发布记录

@auth0/auth0-server-js 共发布 24 个版本,首次发布于 2025/03/28;过去 12 个月发布了 19 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.17.0latest2026/10/2315 天前
1.16.12026/10/021 个月前
1.16.02026/10/011 个月前
1.15.02026/09/221 个月前
1.14.02026/09/151 个月前
1.13.02026/08/312 个月前

关于 @auth0/auth0-server-js 的常见问题

@auth0/auth0-server-js 是什么?

Auth0 Authentication SDK for Server-Side Applications on JavaScript runtimes

如何安装 @auth0/auth0-server-js?

在项目目录运行 npm install @auth0/auth0-server-js,或使用 pnpm add / yarn add / bun add。

@auth0/auth0-server-js 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@auth0/auth0-server-js 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@auth0/auth0-server-js 可以商用吗?

@auth0/auth0-server-js 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@auth0/auth0-server-js 的下载量有多少?

根据 npm 官方下载统计,@auth0/auth0-server-js 在 2026/10/07 – 2026/11/05 这 30 天内被下载 228,857 次,日均约 7,629 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@auth0/auth0-server-js 还在维护吗?

最新版本 1.17.0 发布于 2026/10/23(15 天前);至今共发布 24 个版本,其中过去 12 个月发布了 19 个;首次发布于 2025/03/28。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。