Skip to content

Commit 101f032

Browse files
ematipicomatthewp
andauthored
feat: remove experimental flag middleware (#7109)
* fix: middleware for API endpoints * feat: remove experimental flag middleware * chore: rebase and update * chore: check if physical file exists * chore: restore change * merge * merge * fix: remove options, not needed * remove experimental from types * chore: don't have the middleware inside the manifest * Update how redirects work, slightly --------- Co-authored-by: Matthew Phillips <[email protected]>
1 parent 435a231 commit 101f032

File tree

16 files changed

+45
-83
lines changed

16 files changed

+45
-83
lines changed

.changeset/young-flies-allow.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'astro': minor
3+
---
4+
5+
Remove experimental flag for the middleware

examples/middleware/astro.config.mjs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,6 @@ export default defineConfig({
88
mode: 'standalone',
99
}),
1010
experimental: {
11-
middleware: true,
11+
middleware: true
1212
},
1313
});

packages/astro/src/@types/astro.ts

Lines changed: 0 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,6 @@ export interface CLIFlags {
108108
drafts?: boolean;
109109
open?: boolean;
110110
experimentalAssets?: boolean;
111-
experimentalMiddleware?: boolean;
112111
experimentalRedirects?: boolean;
113112
}
114113

@@ -1189,27 +1188,6 @@ export interface AstroUserConfig {
11891188
*/
11901189
customClientDirectives?: boolean;
11911190

1192-
/**
1193-
* @docs
1194-
* @name experimental.middleware
1195-
* @type {boolean}
1196-
* @default `false`
1197-
* @version 2.4.0
1198-
* @description
1199-
* Enable experimental support for Astro middleware.
1200-
*
1201-
* To enable this feature, set `experimental.middleware` to `true` in your Astro config:
1202-
*
1203-
* ```js
1204-
* {
1205-
* experimental: {
1206-
* middleware: true,
1207-
* },
1208-
* }
1209-
* ```
1210-
*/
1211-
middleware?: boolean;
1212-
12131191
/**
12141192
* @docs
12151193
* @name experimental.hybridOutput

packages/astro/src/core/app/index.ts

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import { consoleLogDestination } from '../logger/console.js';
1515
import { error, type LogOptions } from '../logger/core.js';
1616
import { callMiddleware } from '../middleware/callMiddleware.js';
1717
import { prependForwardSlash, removeTrailingForwardSlash } from '../path.js';
18-
import { RedirectComponentInstance } from '../redirects/index.js';
18+
import { RedirectSinglePageBuiltModule } from '../redirects/index.js';
1919
import {
2020
createEnvironment,
2121
createRenderContext,
@@ -29,6 +29,7 @@ import {
2929
createStylesheetElementSet,
3030
} from '../render/ssr-element.js';
3131
import { matchRoute } from '../routing/match.js';
32+
import type { SinglePageBuiltModule } from '../build/types';
3233
export { deserializeManifest } from './common.js';
3334

3435
const clientLocalsSymbol = Symbol.for('astro.locals');
@@ -171,9 +172,9 @@ export class App {
171172
return getSetCookiesFromResponse(response);
172173
}
173174

174-
async #getModuleForRoute(route: RouteData): Promise<ComponentInstance> {
175+
async #getModuleForRoute(route: RouteData): Promise<SinglePageBuiltModule> {
175176
if (route.type === 'redirect') {
176-
return RedirectComponentInstance;
177+
return RedirectSinglePageBuiltModule;
177178
} else {
178179
const importComponentInstance = this.#manifest.pageMap.get(route.component);
179180
if (!importComponentInstance) {
@@ -182,14 +183,14 @@ export class App {
182183
);
183184
}
184185
const built = await importComponentInstance();
185-
return built.page();
186+
return built;
186187
}
187188
}
188189

189190
async #renderPage(
190191
request: Request,
191192
routeData: RouteData,
192-
mod: ComponentInstance,
193+
page: SinglePageBuiltModule,
193194
status = 200
194195
): Promise<Response> {
195196
const url = new URL(request.url);
@@ -214,6 +215,7 @@ export class App {
214215
}
215216

216217
try {
218+
const mod = (await page.page()) as any;
217219
const renderContext = await createRenderContext({
218220
request,
219221
origin: url.origin,
@@ -224,7 +226,7 @@ export class App {
224226
links,
225227
route: routeData,
226228
status,
227-
mod: mod as any,
229+
mod,
228230
env: this.#env,
229231
});
230232

@@ -235,7 +237,7 @@ export class App {
235237
site: this.#env.site,
236238
adapterName: this.#env.adapterName,
237239
});
238-
const onRequest = this.#manifest.middleware?.onRequest;
240+
const onRequest = page.middleware?.onRequest;
239241
let response;
240242
if (onRequest) {
241243
response = await callMiddleware<Response>(
@@ -268,11 +270,12 @@ export class App {
268270
async #callEndpoint(
269271
request: Request,
270272
routeData: RouteData,
271-
mod: ComponentInstance,
273+
page: SinglePageBuiltModule,
272274
status = 200
273275
): Promise<Response> {
274276
const url = new URL(request.url);
275277
const pathname = '/' + this.removeBase(url.pathname);
278+
const mod = await page.page();
276279
const handler = mod as unknown as EndpointHandler;
277280

278281
const ctx = await createRenderContext({
@@ -285,13 +288,7 @@ export class App {
285288
mod: handler as any,
286289
});
287290

288-
const result = await callEndpoint(
289-
handler,
290-
this.#env,
291-
ctx,
292-
this.#logging,
293-
this.#manifest.middleware
294-
);
291+
const result = await callEndpoint(handler, this.#env, ctx, this.#logging, page.middleware);
295292

296293
if (result.type === 'response') {
297294
if (result.response.headers.get('X-Astro-Response') === 'Not-Found') {

packages/astro/src/core/app/types.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { MarkdownRenderingOptions } from '@astrojs/markdown-remark';
22
import type {
33
AstroMiddlewareInstance,
4+
ComponentInstance,
45
RouteData,
56
SerializedRouteData,
67
SSRComponentMetadata,
@@ -49,7 +50,6 @@ export interface SSRManifest {
4950
entryModules: Record<string, string>;
5051
assets: Set<string>;
5152
componentMetadata: SSRResult['componentMetadata'];
52-
middleware?: AstroMiddlewareInstance<unknown>;
5353
}
5454

5555
export type SerializedSSRManifest = Omit<

packages/astro/src/core/build/generate.ts

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ import { debug, info } from '../logger/core.js';
4141
import { callMiddleware } from '../middleware/callMiddleware.js';
4242
import {
4343
getRedirectLocationOrThrow,
44-
RedirectComponentInstance,
44+
RedirectSinglePageBuiltModule,
4545
routeIsRedirect,
4646
} from '../redirects/index.js';
4747
import { createEnvironment, createRenderContext, renderPage } from '../render/index.js';
@@ -69,10 +69,6 @@ import type {
6969
} from './types';
7070
import { getTimeStat } from './util.js';
7171

72-
const StaticMiddlewareInstance: AstroMiddlewareInstance<unknown> = {
73-
onRequest: (ctx, next) => next(),
74-
};
75-
7672
function createEntryURL(filePath: string, outFolder: URL) {
7773
return new URL('./' + filePath + `?time=${Date.now()}`, outFolder);
7874
}
@@ -94,11 +90,7 @@ async function getEntryForRedirectRoute(
9490
}
9591
}
9692

97-
return {
98-
page: () => Promise.resolve(RedirectComponentInstance),
99-
middleware: StaticMiddlewareInstance,
100-
renderers: [],
101-
};
93+
return RedirectSinglePageBuiltModule;
10294
}
10395

10496
function shouldSkipDraft(pageModule: ComponentInstance, settings: AstroSettings): boolean {

packages/astro/src/core/build/plugins/plugin-middleware.ts

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import type { Plugin as VitePlugin } from 'vite';
22
import { MIDDLEWARE_PATH_SEGMENT_NAME } from '../../constants.js';
3-
import { addRollupInput } from '../add-rollup-input.js';
43
import type { BuildInternals } from '../internal.js';
54
import type { AstroBuildPlugin } from '../plugin';
65
import type { StaticBuildOptions } from '../types';
@@ -13,14 +12,9 @@ export function vitePluginMiddleware(
1312
): VitePlugin {
1413
return {
1514
name: '@astro/plugin-middleware',
16-
options(options) {
17-
if (opts.settings.config.experimental.middleware) {
18-
return addRollupInput(options, [MIDDLEWARE_MODULE_ID]);
19-
}
20-
},
2115

2216
async resolveId(id) {
23-
if (id === MIDDLEWARE_MODULE_ID && opts.settings.config.experimental.middleware) {
17+
if (id === MIDDLEWARE_MODULE_ID) {
2418
const middlewareId = await this.resolve(
2519
`${opts.settings.config.srcDir.pathname}/${MIDDLEWARE_PATH_SEGMENT_NAME}`
2620
);

packages/astro/src/core/build/plugins/plugin-pages.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -80,9 +80,10 @@ function vitePluginPages(opts: StaticBuildOptions, internals: BuildInternals): V
8080
imports.push(`import { renderers } from "${RENDERERS_MODULE_ID}";`);
8181
exports.push(`export { renderers };`);
8282

83-
if (opts.settings.config.experimental.middleware) {
84-
imports.push(`import * as _middleware from "${MIDDLEWARE_MODULE_ID}";`);
85-
exports.push(`export const middleware = _middleware;`);
83+
const middlewareModule = await this.resolve(MIDDLEWARE_MODULE_ID);
84+
if (middlewareModule) {
85+
imports.push(`import * as middleware from "${middlewareModule.id}";`);
86+
exports.push(`export { middleware };`);
8687
}
8788

8889
return `${imports.join('\n')}${exports.join('\n')}`;

packages/astro/src/core/build/plugins/plugin-ssr.ts

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,6 @@ function vitePluginSSR(
4848
const imports: string[] = [];
4949
const contents: string[] = [];
5050
const exports: string[] = [];
51-
let middleware;
52-
if (config.experimental?.middleware === true) {
53-
imports.push(`import * as _middleware from "${MIDDLEWARE_MODULE_ID}"`);
54-
middleware = 'middleware: _middleware';
55-
}
5651
let i = 0;
5752
const pageMap: string[] = [];
5853

@@ -84,7 +79,6 @@ import { _privateSetManifestDontUseThis } from 'astro:ssr-manifest';
8479
const _manifest = Object.assign(_deserializeManifest('${manifestReplace}'), {
8580
pageMap,
8681
renderers,
87-
${middleware}
8882
});
8983
_privateSetManifestDontUseThis(_manifest);
9084
const _args = ${adapter.args ? JSON.stringify(adapter.args) : 'undefined'};

packages/astro/src/core/build/static-build.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -179,9 +179,9 @@ async function ssrBuild(
179179
return makeAstroPageEntryPointFileName(chunkInfo.facadeModuleId);
180180
} else if (
181181
// checks if the path of the module we have middleware, e.g. middleware.js / middleware/index.js
182-
chunkInfo.facadeModuleId?.includes('middleware') &&
182+
chunkInfo.moduleIds.find((m) => m.includes('middleware')) !== undefined &&
183183
// checks if the file actually export the `onRequest` function
184-
chunkInfo.exports.includes('onRequest')
184+
chunkInfo.exports.includes('_middleware')
185185
) {
186186
return 'middleware.mjs';
187187
} else if (chunkInfo.facadeModuleId === SSR_VIRTUAL_MODULE_ID) {

0 commit comments

Comments
 (0)