Skip to content

Astro page layout and middleware execution order

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.

I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter

  • C Handbook
  • Command Line Handbook
  • CSS Handbook
  • Express Handbook
  • Git Cheat Sheet
  • Go Handbook
  • HTML Handbook
  • JS Handbook
  • Laravel Handbook
  • Next.js Handbook
  • Node.js Handbook
  • PHP Handbook
  • Python Handbook
  • React Handbook
  • SQL Handbook
  • Svelte Handbook
  • Swift Handbook

JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list