Fastify Basic Auth Middleware

0.0.2 · active · verified Wed Apr 22

This package provides a plug-and-play HTTP Basic Authentication solution designed for use with the Fastify web framework. It supports checking credentials against static user lists or through custom synchronous or asynchronous authorizer functions. As of version 0.0.2, it emphasizes secure credential comparison with a `safeCompare` utility to prevent timing attacks. While its README initially showed Express.js examples, the package is explicitly built for Fastify. It ships with TypeScript types, ensuring type safety for Fastify applications. This plugin is distinct from the `@fastify/basic-auth` core plugin, offering a different API for integrating basic authentication.

Common errors

Warnings

Install

Imports

Quickstart

This example sets up a Fastify server with basic authentication using static user credentials. It protects the `/protected` route, demonstrating how the `fastify-basic-auth-middleware` integrates with Fastify's plugin system and hooks.

import Fastify from 'fastify';
import basicAuthPlugin from 'fastify-basic-auth-middleware';

const fastify = Fastify({ logger: true });

// Register the basic auth plugin with static users
fastify.register(basicAuthPlugin, {
  users: { 'admin': 'supersecret', 'user': 'password123' },
});

// Add a preHandler hook to protect routes with basic authentication
fastify.addHook('preHandler', async (request, reply) => {
  try {
    // The plugin adds 'auth' to the request if credentials are provided
    // and checks them against the configured users/authorizer.
    // If unauthorized, it will automatically send a 401 response.
    if (!request.auth || !request.auth.user) {
      reply.code(401).send('Unauthorized'); // This part is handled by the plugin, but explicitly showing the check
    }
    request.log.info(`Authenticated user: ${request.auth.user}`);
  } catch (err) {
    request.log.error('Authentication error:', err);
    reply.code(500).send('Internal Server Error');
  }
});

// Define a protected route
fastify.get('/protected', async (request, reply) => {
  return { message: `Hello, ${request.auth.user}! You accessed a protected route.` };
});

// Define an unprotected route
fastify.get('/public', async (request, reply) => {
  return { message: 'This is a public route.' };
});

const start = async () => {
  try {
    await fastify.listen({ port: 3000 });
    fastify.log.info(`Server listening on ${fastify.server.address().port}`);
    console.log('Try accessing: http://localhost:3000/protected with admin:supersecret');
    console.log('Try accessing: http://localhost:3000/public');
  } catch (err) {
    fastify.log.error(err);
    process.exit(1);
  }
};

start();

view raw JSON →