Skip to content

Commit

Permalink
fix(middleware): do not import user middleware if not preset (#9057)
Browse files Browse the repository at this point in the history
  • Loading branch information
ematipico authored Nov 10, 2023
1 parent 1e97708 commit 1bc3319
Show file tree
Hide file tree
Showing 13 changed files with 123 additions and 10 deletions.
5 changes: 5 additions & 0 deletions .changeset/chilled-swans-appear.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': patch
---

Correctly infer the presence of an user middleware
10 changes: 8 additions & 2 deletions packages/astro/src/core/middleware/vite-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export function vitePluginMiddleware({ settings }: { settings: AstroSettings }):
let resolvedMiddlewareId: string | undefined = undefined;
const hasIntegrationMiddleware =
settings.middlewares.pre.length > 0 || settings.middlewares.post.length > 0;
let userMiddlewareIsPresent = false;

return {
name: '@astro/plugin-middleware',
Expand All @@ -29,6 +30,7 @@ export function vitePluginMiddleware({ settings }: { settings: AstroSettings }):
const middlewareId = await this.resolve(
`${decodeURI(settings.config.srcDir.pathname)}${MIDDLEWARE_PATH_SEGMENT_NAME}`
);
userMiddlewareIsPresent = !!middlewareId;
if (middlewareId) {
resolvedMiddlewareId = middlewareId.id;
return MIDDLEWARE_MODULE_ID;
Expand Down Expand Up @@ -61,13 +63,17 @@ export function vitePluginMiddleware({ settings }: { settings: AstroSettings }):
const postMiddleware = createMiddlewareImports(settings.middlewares.post, 'post');

const source = `
import { onRequest as userOnRequest } from '${resolvedMiddlewareId}';
${
userMiddlewareIsPresent
? `import { onRequest as userOnRequest } from '${resolvedMiddlewareId}';`
: ''
}
import { sequence } from 'astro:middleware';
${preMiddleware.importsCode}${postMiddleware.importsCode}
export const onRequest = sequence(
${preMiddleware.sequenceCode}${preMiddleware.sequenceCode ? ',' : ''}
userOnRequest${postMiddleware.sequenceCode ? ',' : ''}
${userMiddlewareIsPresent ? `userOnRequest${postMiddleware.sequenceCode ? ',' : ''}` : ''}
${postMiddleware.sequenceCode}
);
`.trim();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { sequence, defineMiddleware } from 'astro:middleware';
import { defineMiddleware } from 'astro:middleware';

export const onRequest = defineMiddleware((context, next) => {
if(context.url.pathname === '/integration-post') {
if (context.url.pathname === '/integration-post') {
return new Response(JSON.stringify({ post: 'works' }), {
headers: {
'content-type': 'application/json'
}
'content-type': 'application/json',
},
});
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { sequence, defineMiddleware } from 'astro:middleware';
import { defineMiddleware } from 'astro:middleware';

export const onRequest = defineMiddleware((context, next) => {
if(context.url.pathname === '/integration-pre') {
if (context.url.pathname === '/integration-pre') {
return new Response(JSON.stringify({ pre: 'works' }), {
headers: {
'content-type': 'application/json'
}
'content-type': 'application/json',
},
});
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import {defineConfig} from "astro/config";
import {fileURLToPath} from "node:url";

export default defineConfig({
integrations: [
{
name: 'my-middleware',
hooks: {
'astro:config:setup':({ addMiddleware }) => {
addMiddleware({
entrypoint: fileURLToPath(new URL('./integration-middleware-pre.js', import.meta.url)),
order: 'pre'
});

addMiddleware({
entrypoint: fileURLToPath(new URL('./integration-middleware-post.js', import.meta.url)),
order: 'post'
});
}
}
}
]
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { defineMiddleware } from 'astro:middleware';

export const onRequest = defineMiddleware((context, next) => {
if (context.url.pathname === '/post') {
return new Response(JSON.stringify({ post: 'works' }), {
headers: {
'content-type': 'application/json',
},
});
}

return next();
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { defineMiddleware } from 'astro:middleware';

export const onRequest = defineMiddleware((context, next) => {
if (context.url.pathname === '/pre') {
return new Response(JSON.stringify({ pre: 'works' }), {
headers: {
'content-type': 'application/json',
},
});
}

return next();
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"name": "@test/middleware-no-user-middlewaqre",
"version": "0.0.0",
"private": true,
"dependencies": {
"astro": "workspace:*"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
const data = Astro.locals;
---

<html>
<head>
<title>Testing</title>
</head>
<body>

<span>Index</span>
<p>{data?.name}</p>
</body>
</html>
Empty file.
Empty file.
25 changes: 25 additions & 0 deletions packages/astro/test/middleware.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,31 @@ describe('Middleware in DEV mode', () => {
expect(json.post).to.equal('works');
});
});

describe('Integration hooks with no user middleware', () => {
before(async () => {
fixture = await loadFixture({
root: './fixtures/middleware-no-user-middleware/',
});
devServer = await fixture.startDevServer();
});

after(async () => {
await devServer.stop();
});

it('Integration middleware marked as "pre" runs', async () => {
let res = await fixture.fetch('/pre');
let json = await res.json();
expect(json.pre).to.equal('works');
});

it('Integration middleware marked as "post" runs', async () => {
let res = await fixture.fetch('/post');
let json = await res.json();
expect(json.post).to.equal('works');
});
});
});

describe('Middleware in PROD mode, SSG', () => {
Expand Down
6 changes: 6 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 1bc3319

Please sign in to comment.