To password protect an Astro site, add middleware that checks the Authorization header for HTTP basic auth credentials and returns a 401 response with a WWW-Authenticate header when they are missing or wrong. The browser then shows its built-in username and password prompt. This works for pages rendered on demand with an adapter; for a fully static site, use your host’s password protection instead.
Key Takeaways
- Basic auth is fine for staging sites, client previews and internal pages; it is not a user account system.
- Middleware can only protect on-demand routes, so set
output: 'server'for whole-site protection.- Keep the username and password in server secrets declared with
astro:env.- Static sites should use host-level protection such as Cloudflare Access or Vercel and Netlify password features.
Declare the credentials
// astro.config.mjs
import { defineConfig, envField } from 'astro/config';
import node from '@astrojs/node';
export default defineConfig({
output: 'server',
adapter: node({ mode: 'standalone' }),
env: {
schema: {
SITE_USER: envField.string({ context: 'server', access: 'secret' }),
SITE_PASSWORD: envField.string({ context: 'server', access: 'secret' }),
},
},
});
output: 'server' makes every page render on demand, so middleware sees every request. Use whichever adapter matches your host. Set SITE_USER and SITE_PASSWORD in .env locally and in your host’s environment variables; never commit them. Our environment variables guide explains astro:env in full.
The middleware
// src/middleware.ts
import { defineMiddleware } from 'astro:middleware';
import { SITE_USER, SITE_PASSWORD } from 'astro:env/server';
function safeEqual(a: string, b: string) {
if (a.length !== b.length) return false;
let diff = 0;
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
return diff === 0;
}
const challenge = () =>
new Response('Authentication required', {
status: 401,
headers: { 'WWW-Authenticate': 'Basic realm="Staging", charset="UTF-8"' },
});
export const onRequest = defineMiddleware((context, next) => {
const header = context.request.headers.get('authorization') ?? '';
if (!header.startsWith('Basic ')) return challenge();
let decoded = '';
try {
decoded = atob(header.slice(6));
} catch {
return challenge();
}
const sep = decoded.indexOf(':');
const user = decoded.slice(0, sep);
const pass = decoded.slice(sep + 1);
if (sep < 0 || !safeEqual(user, SITE_USER) || !safeEqual(pass, SITE_PASSWORD)) {
return challenge();
}
return next();
});
How it works:
- The first visit has no
Authorizationheader, so the middleware returns401withWWW-Authenticate: Basic. The browser shows its login dialog. - The browser retries with
Authorization: Basic <base64 of user:password>. - The middleware decodes it and compares both parts.
safeEqualcompares every character so the response time does not reveal how much of a guess was right. - On success it calls
next()and the page renders. The browser keeps sending the header for the rest of the session.
Basic auth sends credentials on every request, encoded but not encrypted, so only use it over HTTPS. All major hosts serve HTTPS by default.
Protect only part of the site
To keep most pages static and lock one section, skip prerendered pages and check the path:
// src/middleware.ts (start of onRequest)
if (context.isPrerendered || !context.url.pathname.startsWith('/preview')) {
return next();
}
Then add export const prerender = false to every page under /preview/. Prerendered pages are built once and served as files, so middleware cannot guard them. For real user accounts with sign-in pages and sessions, see protected routes with middleware.
Fully static sites: protect at the host
If the site has no adapter, there is no request-time code to run. Protect it where the files are served:
| Host | Option |
|---|---|
| Cloudflare Pages | Cloudflare Access in front of the project or its preview URLs |
| Vercel | Deployment Protection settings |
| Netlify | Password protection or basic auth headers on supported plans |
| Your own server | auth_basic in nginx or .htaccess with Apache |
Host-level protection also covers images, scripts and other files in dist/, which middleware on a hybrid site does not. That makes it the better choice for client previews of a whole site, such as a customised Astro theme you are showing before launch.
Remember to keep protected staging sites out of search engines too: add a noindex header or meta tag, since a password prompt alone does not stop links from being discovered.
FAQ
How do I password protect an Astro site?
For a server-rendered site, add middleware that checks the Authorization header for basic auth and returns 401 with WWW-Authenticate: Basic when it is missing or wrong. For a static site, use your host’s password or access protection.
Is basic auth secure enough?
For staging sites and internal previews over HTTPS, yes. It has no logout, no rate limiting and one shared password, so it is not suitable for customer accounts. Use sessions and an auth library for those.
Why does my Astro middleware not protect static pages?
Prerendered pages are generated at build time and served as files, so middleware never runs on visits. Render the pages on demand or protect the site at the host.
Where should I store the basic auth password?
In server-only secrets: declare it with envField.string({ context: 'server', access: 'secret' }) and set the value in your host’s environment variables, not in the repository.