npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@byu-oit-sdk/fastify

v0.11.0

Published

Fastify server utilities to handle authentication using authorization code grant

Readme

@byu-oit-sdk/fastify

Requirements:

  • Node.js 20+
  • npm v9+
  • Fastify v5
  • @fastify/cookie v11+

Breaking Changes

  • @byu-oit-sdk/fastify now requires Node.js 20 or newer.
  • @byu-oit-sdk/fastify now targets Fastify 5 and @fastify/cookie 11 or newer.
  • The default JWT decoding path now uses jose internally instead of fast-jwt.

Installing

In addition to installing this module, you must install and configure a compatible store. Currently only session-dynamo is supported.

npm install @byu-oit-sdk/fastify @byu-oit-sdk/session-dynamo

Introduction

Use this module to configure fastify servers that need to implement the OAuth 2.0 Authorization Code grant type.

This module assumes that the access token returned after the authorization code exchange will be a jwt that it can decode to extract user information. This behavior is configurable by passing in the userInfoCallback function into the plugin configuration.

Options

In addition to the options below, any AuthorizationCodeProvider options may also be passed into the configuration.

| Option | Type | Default | Description | |--------------------|--------|-----------------|--------------------------------------------------------------------------------------------------------------------| | logIn | string | /signin | The path which redirects the caller to the authorization url to sign in. | | logInRedirect | string | / | The path to redirect the caller to after signing in. | | logOut | string | /signout | The path to call to clear a user's session and revoke the access token. | | logOutRedirect | string | / | The path to redirect the caller to after signing out. | | errorRedirect | string | /auth/error | The path to redirect the caller to after an error is encountered during the authorization flow. | | userInfoCookieName | string | user_info | The name of the cookie containing the user information parsed from the token. | | getIdToken | function | (returns the access token) | Configures how the package gets the id token. | | userInfoCallback | function | (returns the decoded token using the getIdToken function) | Configures how the package gets the user information. | | clientId | string | - | The client identifier issued to the client during the registration process. | | clientSecret | string | - | The client secret of the account being used. | | redirectUri | string | - | The redirection endpoint that the authorization server should redirect to after authenticating the resource owner. | | discoveryEndpoint | string | - | Used to configure where the user will be sent to sign in. |

Signing In

  1. For a user to log in, the browser should direct the user to the logIn route.
  2. After the user logs in, the server will redirect the user to the location provided in the redirect query parameter from the login step, or falls back to the logInRedirect option passed into the configuration.
  3. If the user encounters an error, they will be redirected to errorRedirect and an error message will be displayed in the query parameters of the url.

Signing Out

  1. For a user to log out, the browser should direct the user to thelogOut route.
  2. When the user logs out, their session is cleared but the token is not revoked.
  3. After logging out, they will be redirected to the logOutRedirect route.
  4. If the user encounters an error, they will be redirected to errorRedirect and an error message will be displayed in the query parameters of the url.

Usage

import { ByuLogger } from '@byu-oit/logger'
import { AuthorizationCodeFlow, byuOitGetIdToken as getIdToken } from '@byu-oit-sdk/fastify'
import fastifyCookie from '@fastify/cookie'
import { SessionPlugin } from '@byu-oit-sdk/session-fastify'
import Fastify from 'fastify'
import dynamoDbStoreFactory from 'connect-dynamodb'
import env from 'env-var'

/**
 * Environment variable setup.
 */
const secret = env.get('BYU_OIT_SIGNING_SECRET').required().asString()
const table = env.get('SESSION_TABLE').required().asString()
const isProduction = env.get('NODE_ENV').default('development').asEnum(['production', 'development']) === 'production'

/**
 * Initialize fastify with BYU Logger.
 */
export const fastify = Fastify({ logger: ByuLogger() })

/**
 * Must register the \@fastify/cookie plugin. The \@fastify/jwt module depends on \@fastify/cookie.
 */
await fastify.register(fastifyCookie)

let store
if (isProduction) {
    const client = new DynamoDBClient({
        region: env.get('AWS_REGION').required().asString(),
        endpoint: 'http://localhost:8000'
    })
    store = new DynamoSessionStore({ client, tableName: 'sessions' })
}

/**
 *  Must register the \@byu-oit-sdk/session-fastify plugin. You must pass in a session storage option for production environments.
 *  Using the default in-memory storage is highly discouraged because it will cause memory leaks.
 */
await fastify.register(SessionPlugin, { store })

/**
 * AuthorizationCodeProvider options may be passed in the second parameter.
 */
await fastify.register(AuthorizationCodeFlow, { getIdToken })

/**
 * To require authentication for a route, just specify the authenticate function on the request object in the onRequest hook.
 */
fastify.get('/auth/user', { onRequest: [fastify.authenticate] }, (req, reply) => {
    return `Your CES UUID is ${req.session.user.cesUUID}`
})
import { ByuLogger } from '@byu-oit/logger'
import { AuthorizationCodeFlow } from '@byu-oit-sdk/fastify'
import fastifyCookie from '@fastify/cookie'
import { SessionPlugin } from '@byu-oit-sdk/session-fastify'
import Fastify from 'fastify'
import env from 'env-var'
import { decodeJwt } from 'jose'
import { DynamoSessionStore } from '@byu-oit-sdk/session-dynamo'
import { DynamoDBClient } from '@aws-sdk/client-dynamodb'

declare module '@byu-oit-sdk/fastify' {
    interface UserInfo {
        /**
         * Declare your user info properties here
         */
    }
}

const secret = env.get('BYU_OIT_SIGNING_SECRET').required().asString()
const isProduction = env.get('NODE_ENV').default('development').asEnum(['production', 'development']) === 'production'

export const fastify = Fastify({ logger: ByuLogger() })

/**
 * Must register the \@fastify/cookie plugin. The \@fastify/jwt module depends on \@fastify/cookie.
 */
await fastify.register(fastifyCookie)

let store
if (isProduction) {
  const client = new DynamoDBClient({})
  store = new DynamoSessionStore({ client, tableName: 'sessions' })
}

/**
 *  Must register the \@byu-oit-sdk/session-fastify plugin. You must pass in a session storage option for production environments.
 *  Using the default in-memory storage is highly discouraged because it will cause memory leaks.
 */
await fastify.register(SessionPlugin, { store })

await fastify.register(AuthorizationCodeFlow, {
    /**
     * A user info callback function can be supplied to implement a custom way to return the user info data.
     * the default behavior is to decode the access token returned from the oauth provider token endpoint.
     * The context of the `userInfoCallback` function is bound to the FastifyAuthorizationCodeProvider instance.
     */
    userInfoCallback (token) {
        if (typeof token.additional.id_token !== 'string') {
            /** The id token property must exist in the token response body */
            throw Error('Missing or mal-formatted ID token in response from token endpoint. Did you set the right scopes?')
        }
        /** Decode the `id_token` property, which should return the user info object. */
        return decodeJwt(token.additional.id_token)
    }
})

/**
 * To require authentication for a route, just specify the authenticate function on the request object in the onRequest hook.
 */
fastify.get('/auth/user', { onRequest: [fastify.authenticate] }, (req, reply) => {
    return req.session.user
})

Logging in and out

This package sets up two ways for users to log in and out. The main way is to have a link that sends the user to the value passed in as logIn or logOut in the options for the AuthorizationCodeFlow() function (the default is /signin and /auth/signout, respectively). The user could even manually navigate to those routes in their browser.

<a href="/signout">Sign Out</a>
<a href="/signin">Sign In</a>

If you want to have the user be redirected to log in or log out while running server-side code, a set of functions will be added to the fastify reply object in route handlers and such, so you can simply call reply.login(<optional redirect url>) or reply.logout(<optional redirect url>). The parameter for each function is optional and if not provided, the logInRedirect and logOutRedirect values from the options passed into the AuthorizationCodeFlow() function will be used.

fastify.get((request, reply) => {
  if (req.session.data.token == null ) {
    reply.login('/return_to_me_after_login')
  }
})

This package also exposes two functions on your fastify instance: authenticate and autoAuthenticate. To require authentication for a route, just specify the authenticate function on the request object in the onRequest hook. If you use the autoAuthenticate instead, the user will automatically be redirected to the signin route if they attempt to access a protected route without being logged in.