Basic Auth with Next.JS Middleware

Configure Basic Auth in NextJS using Middleware. Straight forward and easy to use.

Lukas Fischer
  • Lukas Fischer

  • Founder & Product Visionary

next.js Routing Middleware

This blog post is part of a series of tech related content. We cover technical concepts, solutions and practical helpers that came out of our daily work.

Recently I had to secure a staging environment of a NextJS application we host on Vercel. In our Drupal development, we usually use Basic Auth features of Apache webserver or with the Shield module. Adding Basic Auth to a NextJS application is not that straight forward, especially when you pregenerate pages with getStaticProps(). Thanks to NextJS Middleware capabilities, there is a simple solution.

The following approach is taken from Vercels official examples GitHub.

Create middleware.ts in the root of your NextJS app.

// middleware.ts import { NextResponse } from 'next/server' import type { NextRequest } from 'next/server' export function middleware(req: NextRequest) {  // Basic Auth example taken from https://github.com/vercel/examples/tree/main/edge-functions/basic-auth-password  const basicAuth = req.headers.get('authorization')  const url = req.nextUrl  if (basicAuth) {    const authValue = basicAuth.split(' ')[1]    const [user, pwd] = atob(authValue).split(':')    if (user === 'username' && pwd === 'password') {      return NextResponse.next()    }  }  url.pathname = '/api/basicauth'  return NextResponse.rewrite(url) } export const config = {  matcher: '/:path*',

Create /pages/api/basicauth.ts

import type { NextApiRequest, NextApiResponse } from 'next' export default function handler(_: NextApiRequest, res: NextApiResponse) {  res.setHeader('WWW-authenticate', 'Basic realm="Secure Area"')  res.statusCode = 401  res.end(`Auth Required.`) }

That will do the job. Change the username and password according to your needs.


13.10.22

Newsletter abonnieren.