Vite HTTP Basic Auth Plugin

1.0.2 · active · verified Wed Apr 22

vite-plugin-http-basic-auth is a Vite plugin designed to add HTTP Basic Authentication support to the Vite development server and preview server. It is currently at version 1.0.2. As a plugin for Vite, its release cadence is generally tied to the Vite ecosystem, with updates provided as needed for compatibility or new features. This plugin is particularly useful for protecting development or staging environments that are exposed publicly, requiring credentials before allowing access. Key differentiators include its simple configuration within the Vite `defineConfig`, direct integration with environment variables for credentials, and optional enablement for both development and preview modes. It leverages standard HTTP Basic Auth, making it widely compatible with browsers and other clients.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to configure HTTP Basic Authentication using environment variables for a Vite project, protecting both the development and preview servers.

import { defineConfig, loadEnv } from 'vite';
import httpAuth from 'vite-plugin-http-basic-auth';

// To run this example, create a .env file:
// VITE_AUTH_USERNAME_DEV=devuser
// VITE_AUTH_PASSWORD_DEV=devpass
// VITE_AUTH_REALM=SecureDevSite

export default defineConfig(({ command, mode }) => {
  const env = loadEnv(mode, process.cwd(), '');

  return {
    plugins: [
      httpAuth([{
        username: env.VITE_AUTH_USERNAME_DEV ?? '', // Use environment variables for credentials
        password: env.VITE_AUTH_PASSWORD_DEV ?? ''
      }], {
        realm: env.VITE_AUTH_REALM ?? 'Protected Area', // Optional: customize the realm
        useInServer: true,   // Default: true, enables auth for 'npm run dev'
        useInPreview: true   // Default: true, enables auth for 'npm run preview'
      })
    ]
  };
});

view raw JSON →