#context.locals becomes undefined

3 messages · Page 1 of 1 (latest)

civic folio
#

I use this middleware:

export const onRequest = defineMiddleware(async (context, next) => {
if (!isProtected(context.url.pathname)) {
return next()
}

const token = context.cookies.get(TOKEN)?.value
const validationResult = await verifyAuth(
token,
context.url.pathname.split('/')[2],
)

switch (validationResult.status) {
case 'authorized':
const jwtVerifyResult = await jwtVerify(token, secret)
const { name } = jwtVerifyResult.payload
console.log('middleware: ', name)
context.locals.player = name
return next()

I access it in an astro file like this:
const nameOfPlayer = Astro.locals.player

After I navigate to another route Astro.locals.player becomes undefined but I still need that name

rustic orbitBOT
#

Hi @civic folio. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

The locals object in Astro's middleware is designed to live and die within a single Astro route. This means that when your route page is rendered, locals won’t exist anymore and a new one will be created for the next route. This is why Astro.locals.player becomes undefined when you navigate to another route. If you need to persist data across multiple page requests, you'll need to store it elsewhere, such as in a cookie or session storage.

Here's the relevant extract from the Astro documentation:

locals is an object that lives and dies within a single Astro route; when your route page is rendered, locals won’t exist anymore and a new one will be created. Information that needs to persist across multiple page requests must be stored elsewhere. source (https://docs.astro.build/en/guides/middleware/)

In your case, you could consider storing the name in a cookie after it's verified, and then retrieve it from the cookie in your Astro pages.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: