Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/stupid-snails-build.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@astrojs/node': minor
'astro': minor
---

Add support for running middleware on prerendered (static) pages in standalone mode
1 change: 1 addition & 0 deletions examples/static-with-middleware/.codesandbox/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
FROM node:18-bullseye
24 changes: 24 additions & 0 deletions examples/static-with-middleware/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# build output
dist/
# generated types
.astro/

# dependencies
node_modules/

# logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*


# environment variables
.env
.env.production

# macOS-specific files
.DS_Store

# jetbrains setting folder
.idea/
4 changes: 4 additions & 0 deletions examples/static-with-middleware/.vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"recommendations": ["astro-build.astro-vscode"],
"unwantedRecommendations": []
}
11 changes: 11 additions & 0 deletions examples/static-with-middleware/.vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"version": "0.2.0",
"configurations": [
{
"command": "./node_modules/.bin/astro dev",
"name": "Development server",
"request": "launch",
"type": "node-terminal"
}
]
}
66 changes: 66 additions & 0 deletions examples/static-with-middleware/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# Astro Starter Kit: Static Pages with Runtime Middleware

```sh
npm create astro@latest -- --template static-with-middleware
```

[![Open in StackBlitz](https://developer.stackblitz.com/img/open_in_stackblitz.svg)](https://stackblitz.com/github/withastro/astro/tree/latest/examples/static-with-middleware)
[![Open with CodeSandbox](https://assets.codesandbox.io/github/button-edit-lime.svg)](https://codesandbox.io/p/sandbox/github/withastro/astro/tree/latest/examples/static-with-middleware)
[![Open in GitHub Codespaces](https://github.com/codespaces/badge.svg)](https://codespaces.new/withastro/astro?devcontainer_path=.devcontainer/static-with-middleware/devcontainer.json)

> 🧑‍🚀 **Seasoned astronaut?** Delete this file. Have fun!

This example demonstrates how to use middleware with statically generated pages using the Node adapter's `runMiddlewareOnRequest` option.

Features:

- ✅ 🔐 Authentication on static pages - Protect statically generated pages with cookie-based authentication
- ✅ 🚀 Best of both worlds - Get the performance of static pages with the security of runtime checks
- ✅ 🎯 No edge functions required - Runs on your Node.js server, not in a separate edge runtime

## 🚀 Project Structure

Inside of your Astro project, you'll see the following folders and files:

```text
/
├── public/
├── src/
│ ├── content/
│ ├── layouts/
│ ├── pages/
│ ├── content.config.ts
│ └── middleware.ts
├── astro.config.mjs
├── README.md
├── package.json
└── tsconfig.json
```

This example includes a complete authentication flow:

- **Login page** (`/login`) - Form-based login with demo credentials
- **Protected pages** (`/dashboard`, `/entries/secret-post`) - Require authentication
- **Auth API** (`/api/auth/login`, `/api/auth/logout`) - Handle login/logout with cookies
- **Middleware** (`src/middleware.ts`) - Checks `auth-token` cookie before serving protected pages

The Node adapter automatically skips middleware during prerendering, then runs it at request time when serving static files with full cookie/header access.

## 🧞 Commands

All commands are run from the root of the project, from a terminal:

| Command | Action |
| :------------------------ | :----------------------------------------------- |
| `npm install` | Installs dependencies |
| `npm run dev` | Starts local dev server at `localhost:4321` |
| `npm run build` | Build your production site to `./dist/` |
| `npm run preview` | Preview your build locally, before deploying |
| `npm run astro ...` | Run CLI commands like `astro add`, `astro check` |
| `npm run astro -- --help` | Get help using the Astro CLI |

After building, start the server with `node dist/server/entry.mjs` to test the authentication flow.

## 👀 Want to learn more?

Feel free to check [our documentation](https://docs.astro.build) or jump into our [Discord server](https://astro.build/chat).
13 changes: 13 additions & 0 deletions examples/static-with-middleware/astro.config.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// @ts-check
import node from '@astrojs/node';
import { defineConfig } from 'astro/config';

// https://astro.build/config
export default defineConfig({
output: 'static',
adapter: node({
mode: 'standalone',
runMiddlewareOnRequest: true,
}),
integrations: [],
});
17 changes: 17 additions & 0 deletions examples/static-with-middleware/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "@example/static-with-middleware",
"type": "module",
"version": "0.0.1",
"private": true,
"scripts": {
"dev": "astro dev",
"build": "astro build",
"preview": "astro preview",
"astro": "astro",
"server": "node dist/server/entry.mjs"
},
"dependencies": {
"@astrojs/node": "^9.4.6",
"astro": "^5.14.4"
}
}
9 changes: 9 additions & 0 deletions examples/static-with-middleware/public/favicon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
16 changes: 16 additions & 0 deletions examples/static-with-middleware/src/content.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { defineCollection, z } from 'astro:content';
import { glob } from 'astro/loaders';

const entries = defineCollection({
// Load Markdown and MDX files in the `src/content/entries/` directory.
loader: glob({ base: './src/content/entries', pattern: '**/*.{md,mdx}' }),
// Type-check frontmatter using a schema
schema: () =>
z.object({
title: z.string(),
// Transform string to Date object
pubDate: z.coerce.date(),
}),
});

export const collections = { entries };
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
title: 'First post'
pubDate: 'Jul 08 2022'
---

This is my first post!
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
title: 'Second post'
pubDate: 'Jul 15 2022'
---

Another post has been published.
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
title: 'Secret post'
pubDate: 'Jul 22 2022'
---

This post is only visible for users that are logged in.
127 changes: 127 additions & 0 deletions examples/static-with-middleware/src/layouts/Layout.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
---
const { title } = Astro.props;
---

<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>{title}</title>
</head>
<body>
<header>
<nav>
<ul>
<li>
<a href="/"> Home </a>
</li>
<li>
<a href="/login"> Login </a>
</li>
<li>
<a href="/logout"> Logout </a>
</li>
<li>
<a href="/dashboard"> Dashboard </a>
</li>
</ul>
</nav>
<h1>{title}</h1>
</header>
<main>
<slot />
</main>
</body>
</html>

<style is:global>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}

html {
font-family: system-ui, sans-serif;
background: #f6f6f6;
}

body {
max-width: 800px;
margin: 0 auto;
padding: 2rem 1rem;
background: white;
min-height: 100vh;
line-height: 1.6;
}

header {
margin-bottom: 2rem;
padding-bottom: 1rem;
border-bottom: 1px solid #ddd;
}

nav ul {
display: flex;
gap: 1rem;
list-style: none;
margin-bottom: 1rem;
}

a {
color: #08305c;
text-decoration: none;
}

a:hover {
text-decoration: underline;
}

h1 {
color: #333;
margin: 1rem 0;
}

h2 {
color: #444;
margin: 1.5rem 0 0.5rem;
}

p {
margin: 0.5rem 0;
}

form {
margin: 1rem 0;
}

label {
display: block;
margin: 1rem 0 0.25rem;
font-weight: 500;
}

input[type="text"],
input[type="password"] {
width: 100%;
padding: 0.5rem;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 1rem;
}

button {
margin-top: 1rem;
padding: 0.5rem 1.5rem;
background: #0070f3;
color: white;
border: none;
border-radius: 4px;
font-size: 1rem;
cursor: pointer;
}

button:hover {
background: #0051cc;
}
</style>
45 changes: 45 additions & 0 deletions examples/static-with-middleware/src/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { defineMiddleware } from 'astro:middleware';

const AUTH_COOKIE_NAME = 'auth-token';
const REDIRECT_COOKIE_NAME = 'redirect-after-login';

/**
* Middleware runs only during requests, not during build.
*
* IMPORTANT: While this middleware has access to cookies, headers, and request context,
* the Astro page components themselves do NOT have access to this runtime data because
* they are prerendered during the build step. This means:
* - `Astro.cookies.get()` in page components will always return undefined
* - `context.locals` set here won't be accessible in page components
* - Only this middleware can read/write cookies and make decisions based on request data
*
* This is perfect for authentication (redirect to login), but won't work for
* personalizing page content based on cookies/headers.
*/
export const onRequest = defineMiddleware(async (context, next) => {
// Protected paths - require authentication
const protectedPaths = ['/secret', '/dashboard'];
const isProtected = protectedPaths.some((path) => context.originPathname.includes(path));

if (!isProtected) {
return next();
}

// Dummy auth validation
const authToken = context.cookies.get(AUTH_COOKIE_NAME);
const isAuthed = authToken?.value === 'valid-token';

if (!isAuthed) {
const response = context.redirect('/login');
context.cookies.set(REDIRECT_COOKIE_NAME, context.originPathname, {
path: '/',
httpOnly: true,
maxAge: 60 * 5, // 5 minutes
});

return response;
}

// User is authenticated, allow access to the page
return next();
});
7 changes: 7 additions & 0 deletions examples/static-with-middleware/src/pages/404.astro
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
import Layout from '../layouts/Layout.astro';
---

<Layout title="Page not found">
<p>Sorry, we couldn't find the page you were looking for.</p>
</Layout>
Loading
Loading