Can anyone please explain what is context.data in pages functions and how it can be used?
Documentation is at: API reference · Cloudflare Pages docs
Can anyone please explain what is context.data in pages functions and how it can be used?
Documentation is at: API reference · Cloudflare Pages docs
It’s an arbitrary object you can attach data to that will persist during the request. The most common use-cases are for middleware that handles auth and may need to set context.data.username
or similar.
Thank you for the answer. However, this does not work.
I added data to context.data in my middleware. I checked data was there with a console.log.
Then I called context.next() to invoke my function and did console.log on context.data. It was empty. Is this a bug or do I have to do something special to make sure data is passed from my middleware to the api?
Note, I’m using Typescript.
Can you share a minimal reproduction? Did you await context.next()
?
It should be working fine based on your description.
Middleware Function: authenticate
async function authenticate(context) {
console.log('authenticating');
... code -- redacted ...
context.data = {lower:{data:"some data"}};
console.log('middleware context');
console.log(context.data);
return await context.next();
}
}
}
Middleware function: error handler
async function handleErrors(context) {
console.log('handling errors');
try {
return await context.next();
} catch (err) { // uncaught exceptions
console.log('uncaught error');
console.log(err);
return new Response(
'Uncaught Server Error',
{ status: TYPES.HTTP_ERROR.INTERNAL_SERVER_ERROR });
}
}
// Chained middleware: handleErrors runs first
export const onRequest = [handleErrors, authenticate];
Called function: getInfo
export async function onRequest( context ) {
console.log('getInfo');
console.log(context.data);
return new Response(`getInfo`);
}
Result
handling errors
authenticating
middleware context
{ lower: { data: 'some data' } }
getInfo
{}
Please Note: Using Typescript
Hmm, it seems I’m able to reproduce this too. Let me dig in a little and get this in front of the right people if needed.
Turns out this is a bug when you override context.data
in its entirety. I’ve reproduced and reported here:
To work around it, avoid setting context.data
entirely and instead do things like context.data.lower = {...}
.
Thank you. That solved it.
This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.