@auth0/auth0-fastify

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

Auth0 Authentication SDK for Fastify Applications on JavaScript runtimes

原始使用文档
文档目录12 节
  1. Documentation
  2. Features
  3. Getting Started
  4. 1. Install the SDK
  5. 2. Register the Auth0 Fastify plugin
  6. 3. Adding Login and Logout
  7. 4. Protecting Routes
  8. Feedback
  9. Contributing
  10. Raise an issue
  11. Vulnerability Reporting
  12. What is Auth0?

The Auth0 Fastify SDK is a library for implementing user authentication in Fastify applications.

Release Downloads License

📚 Documentation - 🔎 Features - 🚀 Getting Started - 💬 Feedback

Documentation

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

Features

Jump straight to the capability you need.

FeatureWhat it does
Quick startRegister the Auth0 plugin with fastify.register in a few lines
Built-in routes/auth/login, /auth/logout, /auth/callback, back-channel logout
Custom login / logout / callbackRoll your own routes instead of the mounted ones
Configure mounted routesDisable the built-in routes or add account-linking routes
Protect a route with a sessionGate server-rendered pages behind a login session
Get the current session / userRead the authenticated user with getUser() / getSession()
Call an API (getAccessToken)Get an access token to call APIs as the user
PasskeysSign users up and log them in with passkeys, with email and phone verification codes
Custom Token ExchangeCreate a session from an external token without a browser login
Impersonation via Session TransferLog an agent into another app as a customer, audited via the act claim
Multiple Custom Domains (MCD)Resolve the Auth0 domain per request
Custom fetchSwap in your own fetch (proxies, retries, instrumentation)
Discovery cacheControl caching of OIDC discovery metadata and JWKS

Getting Started

1. Install the SDK

npm i @auth0/auth0-fastify

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

2. Register the Auth0 Fastify plugin

Register the Auth0 fastify plugin with the Fastify instance.

import auth0 from '@auth0/auth0-fastify';

fastify.register(auth0, {
  domain: '<AUTH0_DOMAIN>',
  clientId: '<AUTH0_CLIENT_ID>',
  clientSecret: '<AUTH0_CLIENT_SECRET>',
  appBaseUrl: '<APP_BASE_URL>',
  sessionSecret: '<SESSION_SECRET>'
});

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 SESSION_SECRET is the key used to encrypt the session cookie. You can generate a secret using openssl:

openssl rand -hex 64

The APP_BASE_URL is the URL that your application is running on. When developing locally, this is most commonly http://localhost:3000.

[!IMPORTANT]
You will need to register the following URLs in your Auth0 Application via the Auth0 Dashboard:

  • Add http://localhost:3000/auth/callback to the list of Allowed Callback URLs
  • Add http://localhost:3000 to the list of Allowed Logout URLs

Routes

The SDK for Fastify Web Applications mounts 4 main routes:

  1. /auth/login: the login route that the user will be redirected to to initiate an authentication transaction. Supports adding a returnTo querystring parameter to return to a specific URL after login. It also forwards a session_transfer_token querystring parameter to Auth0, along with organization when that parameter accompanies an STT, so this route doubles as the redemption endpoint for Impersonation via Session Transfer.
  2. /auth/logout: the logout route that must be added to your Auth0 application's Allowed Logout URLs
  3. /auth/callback: the callback route that must be added to your Auth0 application's Allowed Callback URLs
  4. /auth/backchannel-logout: the route that will receive a logout_token when a configured Back-Channel Logout initiator occurs

To disable this behavior, you can set the mountRoutes option to false (it's true by default):

fastify.register(auth0, {
  mountRoutes: false
});

Additionally, by setting mountConnectRoutes to true (it's false by default) the SDK also can also mount 4 routes useful for account-linking:

  1. /auth/connect: the route that the user will be redirected to to initiate account linking
  2. /auth/connect/callback: the callback route for account linking that must be added to your Auth0 application's Allowed Callback URLs
  3. /auth/unconnect: the route that the user will be redirected to to initiate account linking
  4. /auth/unconnect/callback: the callback route for account linking that must be added to your Auth0 application's Allowed Callback URLs

[!IMPORTANT]
When mountRoutes is set to false, setting mountConnectRoutes has no effect.

3. Adding Login and Logout

When using the built-in mounted routes, the user can be redirected to /auth/login to initiate the login flow and /auth/logout to log out.

<a href="/auth/logout">Log out</a>
<a href="/auth/login">Log in</a
>

When not using the built-in routes, you want to call the SDK's startInteractiveLogin(), completeInteractiveLogin() and logout() methods:

fastify.get('/custom/login', async (request, reply) => {
  const authorizationUrl = await fastify.auth0Client.startInteractiveLogin(
    {
      authorizationParams: {
        // Custom URL to redirect back to after login to handle the callback.
        // Make sure to configure the URL in the Auth0 Dashboard as an Allowed Callback URL.
        redirect_uri: 'http://localhost:3000/custom/callback',
      }
    },
    { request, reply }
  );

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


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

  reply.redirect('https://localhost:3000');
});

fastify.get('/custom/logout', async (request, reply) => {
  const logoutUrl = await auth0Client.logout({ returnTo: 'https://localhost:3000' }, { request, reply });

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

4. Protecting Routes

In order to protect a Fastify route, you can use the SDK's getSession() method in a custom preHandler:

async function hasSessionPreHandler(request: FastifyRequest, reply: FastifyReply) {
  const session = await fastify.auth0Client!.getSession({ request, reply });

  if (!session) {
    reply.redirect('/auth/login');
  }
}

fastify.get(
  '/profile',
  {
    preHandler: hasSessionPreHandler,
  },
  async (request, reply) => {
    const user = await fastify.auth0Client!.getUser({ request, reply });

    return reply.viewAsync('profile.ejs', {
      name: user!.name,
    });
  }
);

[!IMPORTANT]
The above is to protect server-side rendering routes by the means of a session, and not API routes using a bearer token.

Requesting an Access Token to call an API

If you need to call an API on behalf of the user, you want to specify the audience parameter when registering the plugin. This will make the SDK request an access token for the specified audience when the user logs in.

fastify.register(fastifyAuth0, {
  domain: '<AUTH0_DOMAIN>',
  clientId: '<AUTH0_CLIENT_ID>',
  clientSecret: '<AUTH0_CLIENT_SECRET>',
  audience: '<AUTH0_AUDIENCE>',
  appBaseUrl: '<APP_BASE_URL>',
  sessionSecret: '<SESSION_SECRET>',
});

The AUTH0_AUDIENCE is the identifier of the API you want to call. You can find this in the API section of the Auth0 dashboard.

Retrieving the token can be achieved by using getAccessToken:

const accessTokenResult = await fastify.auth0Client.getAccessToken({ request, reply });
console.log(accessTokenResult.accessToken);

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-fastify 共发布 10 个版本,首次发布于 2025/03/28;过去 12 个月发布了 5 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
1.7.0latest2026/10/2612 天前
1.6.02026/08/063 个月前
1.5.02026/07/074 个月前
1.4.02026/06/174 个月前
1.3.02026/04/106 个月前
1.2.02025/10/021.1 年前

关于 @auth0/auth0-fastify 的常见问题

@auth0/auth0-fastify 是什么?

Auth0 Authentication SDK for Fastify Applications on JavaScript runtimes

如何安装 @auth0/auth0-fastify?

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

@auth0/auth0-fastify 支持 TypeScript 吗?

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

@auth0/auth0-fastify 支持 ESM 还是 CommonJS?

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

@auth0/auth0-fastify 可以商用吗?

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

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

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

@auth0/auth0-fastify 还在维护吗?

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