mirror of
https://github.com/withastro/astro.git
synced 2025-03-31 23:31:30 -05:00
fix(middleware): load while retrieving ssr manifest for prerendering (#9938)
* fix(middleware): load while retrieving ssr manifest for prerendering * add test * add changeset
This commit is contained in:
parent
055bd27d9d
commit
1568afb78a
5 changed files with 24 additions and 0 deletions
5
.changeset/shaggy-sloths-mix.md
Normal file
5
.changeset/shaggy-sloths-mix.md
Normal file
|
@ -0,0 +1,5 @@
|
|||
---
|
||||
"astro": patch
|
||||
---
|
||||
|
||||
Fixes a regression where middleware did not run for prerendered pages and endpoints.
|
|
@ -125,6 +125,13 @@ export class BuildPipeline extends Pipeline {
|
|||
|
||||
const renderersEntryUrl = new URL(`renderers.mjs?time=${Date.now()}`, baseDirectory);
|
||||
const renderers = await import(renderersEntryUrl.toString());
|
||||
|
||||
const middleware = await import(new URL('middleware.mjs', baseDirectory).toString())
|
||||
.then((mod) => mod.onRequest)
|
||||
// middleware.mjs is not emitted if there is no user middleware
|
||||
// in which case the import fails with ERR_MODULE_NOT_FOUND, and we fall back to a no-op middleware
|
||||
.catch(() => manifest.middleware);
|
||||
|
||||
if (!renderers) {
|
||||
throw new Error(
|
||||
"Astro couldn't find the emitted renderers. This is an internal error, please file an issue."
|
||||
|
@ -133,6 +140,7 @@ export class BuildPipeline extends Pipeline {
|
|||
return {
|
||||
...manifest,
|
||||
renderers: renderers.renderers as SSRLoadedRenderer[],
|
||||
middleware
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
@ -40,6 +40,8 @@ const first = defineMiddleware(async (context, next) => {
|
|||
status: 200,
|
||||
headers: response.headers,
|
||||
});
|
||||
} else if (context.url.pathname === '/prerendered/') {
|
||||
context.locals.canBeReadDuringPrerendering = "yes they can!";
|
||||
} else {
|
||||
if (context.url.pathname === '/') {
|
||||
context.cookies.set('foo', 'bar');
|
||||
|
|
4
packages/astro/test/fixtures/middleware space/src/pages/prerendered.astro
vendored
Normal file
4
packages/astro/test/fixtures/middleware space/src/pages/prerendered.astro
vendored
Normal file
|
@ -0,0 +1,4 @@
|
|||
---
|
||||
export const prerender = true
|
||||
---
|
||||
<p>{Astro.locals.canBeReadDuringPrerendering}</p>
|
|
@ -278,6 +278,11 @@ describe('Middleware API in PROD mode, SSR', () => {
|
|||
expect(response.headers.get('content-type')).equal('text/html');
|
||||
});
|
||||
|
||||
it('can set locals for prerendered pages to use', async () => {
|
||||
const text = await fixture.readFile("/client/prerendered/index.html")
|
||||
expect(text.includes('<p>yes they can!</p>')).to.be.true;
|
||||
})
|
||||
|
||||
// keep this last
|
||||
it('the integration should receive the path to the middleware', async () => {
|
||||
fixture = await loadFixture({
|
||||
|
|
Loading…
Add table
Reference in a new issue