Basic page access control with Astro

There are many ways to control access to a web page. Depending on your requirements, you may rely on a CDN for that authentication layer. You may also use a node package in your framework of choice to integrate with third-party providers like Google or GitHub.

Sometimes, you’ll want a simple way to assert that a user has a basic password to access a page without including a load of other libraries or services.

Thanks to Astro’s hybrid rendering, introduced in Astro 2.0, you can now select which pages you want to server-side render and which you wish to compile statically.

Let’s say you’ve got a page called secret.astro that will be exposed as a page on your site under We can use the following code at the head of that file to ensure the user passes a password parameter to access the page.

export const prerender = false;

import { PAGE_PASSWORD } from '../consts';

const password = Astro.url.searchParams.get('password');
const authenticated = password == PAGE_PASSWORD;

if (!authenticated)
	return Astro.redirect("/404");

Secret content goes here.

The prerender = false tells Astro not to statically compile this page (to ensure the authentication check is done every time the page is accessed). We’re also storing the password value in our constants file provided by Astro; however, it would probably make more sense to move this to an environment variable to ensure we’re not storing it in version control.

Now, whenever someone tries to access, they’ll need to provide the password as a parameter with