Skip to main content

Basic Authentication

This guide explains how to protect your Docusaurus site hosted on Vercel using Edge Middleware with inline Basic Auth credentials.


1. Install @vercel/edge

Add the Edge runtime package to your project dependencies:

npm install @vercel/edge@^1.2.2

Or update your package.json manually:

{
"dependencies": {
"@vercel/edge": "^1.2.2"
}
}

2. Create Middleware File

At the root of your repo, create a file named middleware.js (or middleware.ts if you prefer TypeScript).

import { next } from '@vercel/edge'

export const config = {
matcher: ['/(.*)'], // Protect all routes
}

export default function middleware(req) {
const authHeader = req.headers.get('authorization')

if (authHeader && authHeader.startsWith('Basic ')) {
const base64 = authHeader.split(' ')[1]
const [user, pwd] = atob(base64).split(':')

// Inline credentials
if (user === 'user' && pwd === 'passwd') {
return next()
}
}

return new Response('Authentication required!', {
status: 401,
headers: {
'WWW-Authenticate': "Basic realm='Secure Area'",
},
})
}

3. How It Works

  • When a visitor opens your site, the middleware intercepts the request.
  • If the Authorization header contains the correct username/password (user:passwd), the request proceeds.
  • Otherwise, the middleware responds with 401 Unauthorized and the browser shows a login prompt.

4. Security

  • Vercel automatically serves your site over HTTPS, so credentials are not exposed in plain text.
  • The example uses hardcoded credentials for simplicity. For production, replace them with environment variables:
const userEnv = process.env.BASIC_AUTH_USERNAME
const passEnv = process.env.BASIC_AUTH_PASSWORD
  • You can adjust the matcher to protect only certain paths (e.g., ['/'] for just the homepage).

5. Deploy

  • Commit and push your changes to GitHub.
  • Vercel will automatically rebuild your Docusaurus site and apply the middleware.
  • Visit your site — you should now see a browser login prompt before accessing content.