In this how-to, I will show you how to add HTTP basic auth to your next.js 14 App. Basic Auth is a feature Vercel offers, but only for the Pro Plan. So let's do it on your own to save some money ;-)

Sometimes you need an easy authentication for small projects or the dev stage. Here basic auth comes into the game and the good thing is ->
All the browsers have native support for HTTP Basic Authentication.

We need an API route and a middleware file. Below is the middleware file
# Middleware.ts
import { NextRequest, NextResponse } from "next/server";
export const config = {
matcher: ["/", "/index"],
};
export function middleware(req: NextRequest) {
// Getting the Pup IP from the request
const { ip } = req;
// console.log("Middleware IP:", ip);
const basicAuth = req.headers.get("authorization");
const url = req.nextUrl;
// Bypass the basic auth on a certain env variable and Pub IP
if (
process.env.LOCAL_URL === "http://localhost:3000" &&
ip !== "xx.xxx.xxx.xxx"
) {
if (basicAuth) {
const authValue = basicAuth.split(" ")[1];
const [user, pwd] = atob(authValue).split(":");
const validUser = process.env.BASIC_AUTH_USER;
const validPassWord = process.env.BASIC_AUTH_PASSWORD;
if (user === validUser && pwd === validPassWord) {
return NextResponse.next();
}
}
url.pathname = "/api/basicauth";
return NextResponse.rewrite(url);
}
}the corresponding .env.local file
# Basic Auth -.env.local
BASIC_AUTH_USER=testuser
BASIC_AUTH_PASSWORD="testpassword"and the route.ts for the basic auth route
# route.ts
export async function GET(request: Request) {
console.log("GET /api/basicauth/route.ts");
return new Response("Authentication Required!", {
status: 401,
headers: {
"WWW-Authenticate": "Basic realm='private_pages'",
},
});
}Keep in mind, that here we can see a very simple middleware integration. If you plan to use localization/internationalization or to use data from a headless CMS, then the middleware.ts file will look quite different and more complex.
Github-Repo: https://github.com/cloudapp-dev/nextjs14-middleware-basic-auth
Cloudapp-dev
Thank you for reading until the end. Before you go:
- Please consider clapping and following the writer! 👏
- Visit cloudapp.dev to find out more about how we are supporting the dev community around the world.