Skip to content

Commit

Permalink
add ability to pass middleware to @astrojs/node when using standalone…
Browse files Browse the repository at this point in the history
… mode
  • Loading branch information
Neville Mehta authored and Neville Mehta committed Jul 20, 2024
1 parent a6c4e67 commit 9a04a07
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 1 deletion.
3 changes: 3 additions & 0 deletions packages/integrations/node/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ export default function createIntegration(userOptions: UserOptions): AstroIntegr
if (!userOptions?.mode) {
throw new AstroError(`Setting the 'mode' option is required.`);
}
if (userOptions.mode !== 'standalone' && userOptions.standaloneMiddleware) {
throw new AstroError(`'standaloneMiddleware' option is only available in 'standalone' mode.`);
}

let _options: Options;
return {
Expand Down
4 changes: 3 additions & 1 deletion packages/integrations/node/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ export function createExports(manifest: SSRManifest, options: Options) {
options: options,
handler:
options.mode === 'middleware' ? createMiddleware(app) : createStandaloneHandler(app, options),
startServer: () => startServer(app, options),
startServer: () => {
startServer(app, options)
},
};
}

Expand Down
8 changes: 8 additions & 0 deletions packages/integrations/node/src/standalone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ export default function standalone(app: NodeApp, options: Options) {
const host = process.env.HOST ?? hostOptions(options.host);
const handler = createStandaloneHandler(app, options);
const server = createServer(handler, host, port);

// optionally add standalone middleware (if passed)
if (options.standaloneMiddleware) {
import(options.standaloneMiddleware)
.then((middleware) => server.server.addListener('request', middleware))
.catch(() => {});
}

server.server.listen(port, host);
if (process.env.ASTRO_NODE_LOGGING !== 'disabled') {
logListeningOn(app.getAdapterLogger(), server.server, options);
Expand Down
4 changes: 4 additions & 0 deletions packages/integrations/node/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ export interface UserOptions {
* - 'standalone' - Build to a standalone server. The server starts up just by running the built script.
*/
mode: 'middleware' | 'standalone';
/**
* Optional file path that (default) exports middleware function to be used in the standalone mode.
*/
standaloneMiddleware?: string;
}

export interface Options extends UserOptions {
Expand Down

0 comments on commit 9a04a07

Please sign in to comment.