
Security News
PolinRider: North Korea-Linked Supply Chain Campaign Expands Across Open Source Ecosystems
PolinRider expands across npm, Packagist, Go modules, and Chrome extensions, using hidden loaders to target developer environments.
@auth0/auth0-fastify
Advanced tools
Auth0 Authentication SDK for Fastify Applications on JavaScript runtimes
The Auth0 Fastify SDK is a library for implementing user authentication in Fastify applications.
📚 Documentation - 🚀 Getting Started - 💬 Feedback
npm i @auth0/auth0-fastify
This library requires Node.js 20 LTS and newer LTS versions.
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/callbackto the list of Allowed Callback URLs- Add
http://localhost:3000to the list of Allowed Logout URLs
The SDK for Fastify Web Applications mounts 4 main routes:
/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./auth/logout: the logout route that must be added to your Auth0 application's Allowed Logout URLs/auth/callback: the callback route that must be added to your Auth0 application's Allowed Callback URLs/auth/backchannel-logout: the route that will receive a logout_token when a configured Back-Channel Logout initiator occursTo 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:
/auth/connect: the route that the user will be redirected to to initiate account linking/auth/connect/callback: the callback route for account linking that must be added to your Auth0 application's Allowed Callback URLs/auth/unconnect: the route that the user will be redirected to to initiate account linking/auth/unconnect/callback: the callback route for account linking that must be added to your Auth0 application's Allowed Callback URLs[!IMPORTANT]
WhenmountRoutesis set tofalse, settingmountConnectRouteshas no effect.
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);
});
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.
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);
We appreciate feedback and contribution to this repo! Before you get started, please read the following:
To provide feedback or report a bug, please raise an issue on our issue tracker.
Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.
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.
FAQs
Auth0 Authentication SDK for Fastify Applications on JavaScript runtimes
The npm package @auth0/auth0-fastify receives a total of 1,175 weekly downloads. As such, @auth0/auth0-fastify popularity was classified as popular.
We found that @auth0/auth0-fastify demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 18 open source maintainers collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
PolinRider expands across npm, Packagist, Go modules, and Chrome extensions, using hidden loaders to target developer environments.

Security News
Open source attacks are accelerating as AI coding agents pull in dependencies faster, with less human review.

Research
/Security News
Malicious Chrome and Firefox extensions posed as free VPNs while stealing clipboard data through later extension updates.