Blog
02.10.2023

Basic Auth with Next.JS Middleware

Configure Basic Auth in NextJS using Middleware. Straight forward and easy to use.
Lukas Fischer
Gründer, Digital Consultant
+41 41 450 10 66
+41 76 413 43 43

Checkout NodeHive Headless CMS.

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.

1. 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*',
}

2. 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.

Are you a remote frontend developer?

We are looking for developers who want to join a purpose driven swiss digital agency. Check jobs.netnode.ch for open vacancies.

Haben Sie eine Frage? Vereinbaren Sie jetzt einen kostenlosen Termin mit
+41 41 450 10 66
+41 76 413 43 43