Skip to content

Astro page layout and middleware execution order

New Course Coming Soon:

Get Really Good at Git

One thing I discovered the hard way (through trial and error) is the order in which pages, layouts and the middleware are called in Astro.

I was doing something related to caching, and I had a workflow where I was doing something in a page, like setting a response header property, or setting a value in Astro.locals :

---
Astro.locals.test = 'test'
Astro.response.headers.set('test', 'test')
---

<p>test</p>

After doing so, I had access to those values after calling next() in the middleware:

import type { MiddlewareHandler } from 'astro'

export const onRequest: MiddlewareHandler = async (context, next) => {

	const response = await next()
	
	console.log(context.locals.test)
	console.log(response.headers.get('test'))

	return response
}

Then I decided to move some of the logic I had in the page in a layout, because I was duplicating some portion of code across multiple pages:

---
import Layout from '@layouts/Layout.astro'
---

<Layout />

In this layout I did the exact same thing I had in the page, previously:

---
Astro.locals.test = 'test'
Astro.response.headers.set('test', 'test')
---

<p>test</p>

but to my surprise, none of those values were now available in the middleware.

Turns out that (to my understanding) the order of execution is different.

The page code is ran calling next() in the middleware.

The layout code is ran after the middleware runs.

To fix my problem I eventually moved some of the logic I had in the middleware to my layout.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Read my Astro Tutorial on The Valley of Code

Here is how can I help you: