Skip to content
Migrating from NextAuth.js v4? Read our migration guide.
API reference
@auth/fastify

@auth/fastify

⚠️

@auth/fastify is currently experimental. The API will change in the future.

Fastify Auth is the official Fastify integration for Auth.js. It provides a simple way to add authentication to your Fastify app in a few lines of code.

Installation

npm install @auth/fastify

Usage

src/routes/auth.route.ts
import { FastifyAuth } from "@auth/fastify"
import GitHub from "@auth/fastify/providers/github"
import Fastify from "fastify"
 
// If app is served through a proxy, trust the proxy to allow HTTPS protocol to be detected
const fastify = Fastify({ trustProxy: true });
 
fastify.register(FastifyAuth({ providers: [ GitHub ] }), { prefix: '/auth' })

Don’t forget to set the AUTH_SECRET environment variable. This should be a minimum of 32 characters, random string. On UNIX systems you can use openssl rand -hex 32 or check out https://generate-secret.vercel.app/32.

You will also need to load the environment variables into your runtime environment. For example in Node.js with a package like dotenv or Deno.env in Deno.

Provider Configuration

The callback URL used by the providers must be set to the following, unless you mount the FastifyAuth handler on a different path:

[origin]/auth/callback/[provider]

Signing in and signing out

Once your application is mounted you can sign in or out by making requests to the following REST API endpoints from your client-side code. NB: Make sure to include the csrfToken in the request body for all sign-in and sign-out requests.

Managing the session

If you are using Fastify with a template engine (e.g @fastify/view with EJS, Pug), you can make the session data available to all routes via a preHandler hook as follows

app.ts
import { getSession } from "@auth/fastify"
 
// Decorating the reply is not required but will optimise performance
// Only decorate the reply with a value type like null, as reference types like objects are shared among all requests, creating a security risk.
fastify.decorateReply('session', null)
 
export async function authSession(req: FastifyRequest, reply: FastifyReply) {
  reply.session = await getSession(req, authConfig)
}
 
fastify.addHook("preHandler", authSession)
 
// Now in your route
fastify.get("/", (req, reply) => {
  const session = reply.session;
  reply.view("index.pug", { user: session?.user })
})

Note for TypeScript, you may want to augment the Fastify types to include the session property on the reply object. This can be done by creating a @types/fastify/index.d.ts file:

@types/fastify/index.d.ts
import { Session } from "@auth/core/types";
declare module "fastify" {
  interface FastifyReply {
    session: Session | null;
  }
}

You may need to add "typeRoots": ["@types"] to compilerOptions in your tsconfig.json.

Authorization

You can protect routes with hooks by checking for the presence of a session and then redirect to a login page if the session is not present.

export async function authenticatedUser(
  req: FastifyRequest,
  reply: FastifyReply
) {
  reply.session ??= await getSession(req, authConfig);
  if (!reply.session?.user) {
    reply.redirect("/auth/signin?error=SessionRequired");
  }
}

Per Route

To protect a single route, simply register the preHandler hook to the route as follows:

app.ts
// This route is protected
fastify.get("/profile", { preHandler: [authenticatedUser] }, (req, reply) => {
  const session = reply.session;
  reply.view("profile.pug", { user: session?.user })
});
 
// This route is not protected
fastify.get("/", (req, reply) => {
  reply.view("index");
});

Per Group of Routes

To protect a group of routes, create a plugin and register the authenication hook and routes to the instance as follows:

app.ts
fastify.register(
  async (instance) => {
    // All routes on this instance will be protected because of the preHandler hook
    instance.addHook("preHandler", authenticatedUser)
 
    instance.get("/", (req, reply) => {
      reply.view("protected.pug")
    })
    
    instance.get("/me", (req, reply) => {
      reply.send(reply.session?.user)
    })
  },
  { prefix: "/protected" }
)

Account

Usually contains information about the provider being used and also extends TokenSet, which is different tokens returned by OAuth Providers.

Extends

  • Partial<OpenIDTokenEndpointResponse>

Properties

access_token?

optional readonly access_token: string;
Inherited from

Partial.access_token

authorization_details?

optional readonly authorization_details: AuthorizationDetails[];
Inherited from

Partial.authorization_details

expires_at?

optional expires_at: number;

Calculated value based on OAuth2TokenEndpointResponse.expires_in.

It is the absolute timestamp (in seconds) when the OAuth2TokenEndpointResponse.access_token expires.

This value can be used for implementing token rotation together with OAuth2TokenEndpointResponse.refresh_token.

See

expires_in?

optional readonly expires_in: number;
Inherited from

Partial.expires_in

id_token?

optional readonly id_token: string;
Inherited from

Partial.id_token

provider

provider: string;

Provider’s id for this account. E.g. “google”. See the full list at https://authjs.dev/reference/core/providers

providerAccountId

providerAccountId: string;

This value depends on the type of the provider being used to create the account.

  • oauth/oidc: The OAuth account’s id, returned from the profile() callback.
  • email: The user’s email address.
  • credentials: id returned from the authorize() callback

refresh_token?

optional readonly refresh_token: string;
Inherited from

Partial.refresh_token

scope?

optional readonly scope: string;
Inherited from

Partial.scope

token_type?

optional readonly token_type: Lowercase<string>;

NOTE: because the value is case insensitive it is always returned lowercased

Inherited from

Partial.token_type

type

type: ProviderType;

Provider’s type for this account

userId?

optional userId: string;

id of the user this account belongs to

See

https://authjs.dev/reference/core/adapters#adapteruser


DefaultSession

Extended by

Properties

expires

expires: string;

user?

optional user: User;

Profile

The user info returned from your OAuth provider.

See

https://openid.net/specs/openid-connect-core-1_0.html#StandardClaims

Indexable

[claim: string]: unknown

Properties

address?

optional address: null | {
  country: null | string;
  formatted: null | string;
  locality: null | string;
  postal_code: null | string;
  region: null | string;
  street_address: null | string;
};

birthdate?

optional birthdate: null | string;

email?

optional email: null | string;

email_verified?

optional email_verified: null | boolean;

family_name?

optional family_name: null | string;

gender?

optional gender: null | string;

given_name?

optional given_name: null | string;

id?

optional id: null | string;

locale?

optional locale: null | string;

middle_name?

optional middle_name: null | string;

name?

optional name: null | string;

nickname?

optional nickname: null | string;

phone_number?

optional phone_number: null | string;

picture?

optional picture: any;

preferred_username?

optional preferred_username: null | string;

profile?

optional profile: null | string;

sub?

optional sub: null | string;

updated_at?

optional updated_at: null | string | number | Date;

website?

optional website: null | string;

zoneinfo?

optional zoneinfo: null | string;

Session

The active session of the logged in user.

Extends

Properties

expires

expires: string;
Inherited from

DefaultSession.expires

user?

optional user: User;
Inherited from

DefaultSession.user


User

The shape of the returned object in the OAuth providers’ profile callback, available in the jwt and session callbacks, or the second parameter of the session callback, when using a database.

Extended by

Properties

email?

optional email: null | string;

id?

optional id: string;

image?

optional image: null | string;

name?

optional name: null | string;

FastifyAuthConfig

type FastifyAuthConfig: Omit<AuthConfig, "raw">;

GetSessionResult

type GetSessionResult: Promise<Session | null>;

FastifyAuth()

FastifyAuth(config): FastifyPluginAsync

Parameters

ParameterType
configFastifyAuthConfig

Returns

FastifyPluginAsync


getSession()

getSession(req, config): GetSessionResult

Parameters

ParameterType
reqFastifyRequest<RouteGenericInterface, RawServerDefault, IncomingMessage, FastifySchema, FastifyTypeProviderDefault, unknown, FastifyBaseLogger, ResolveFastifyRequestType<FastifyTypeProviderDefault, FastifySchema, RouteGenericInterface>>
configFastifyAuthConfig

Returns

GetSessionResult

Auth.js © Balázs Orbán and Team - 2024