Skip to content

Commit

Permalink
[feat/standalonenode-withmiddleware-doc] Add docs for passing middlew…
Browse files Browse the repository at this point in the history
…are option to be used with standalone mode
  • Loading branch information
Neville Mehta authored and Neville Mehta committed Jul 12, 2024
1 parent c312c0a commit a5ccb26
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions src/content/docs/en/guides/integrations-guide/node.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,68 @@ Controls whether the adapter builds to `middleware` or `standalone` mode.

* `standalone` mode builds to server that automatically starts with the entry module is run. This allows you to more easily deploy your build to a host without any additional code.

### Middleware

Ability to pass middleware to be used `only` with standalone mode. Gives you the ability to use packages such as [http-proxy-middleware](https://www.npmjs.com/package/http-proxy-middleware) in standalone mode.

* `middleware` mode allows the built output to be used as middleware for another Node.js server, like Express.js or Fastify.

```js title="astro.config.mjs"
import { defineConfig } from 'astro/config';
import node from '@astrojs/node';

export default defineConfig({
output: 'server',
adapter: node({
mode: 'standalone',
middleware: `${import.meta.dirname}/src/node_middleware.js`,
}),
});
```
```js title="src/node_middleware.js"
const combineMiddleware = (...middlewares) => {
return (req, res, next) => {
let index = 0;
const run = (err) => {
if (err) {
return next(err);
}
if (index >= middlewares.length) {
return next();
}
const middleware = middlewares[index++];
try {
middleware(req, res, run);
} catch (error) {
next(error);
}
};
run();
};
};
const middleware_one = (req, res, next) => {
if (req.url === '/middleware-one') {
res.end('This is middleware one');
} else {
next();
}
};
const middleware_two = (req, res, next) => {
if (req.url === '/middleware-two') {
res.end('This is middleware two');
} else {
next();
}
};
export default combineMiddleware(middleware_one, middleware_two);
```
## Usage
First, [performing a build](/en/guides/deploy/#building-your-site-locally). Depending on which `mode` selected (see above) follow the appropriate steps below:
Expand Down

0 comments on commit a5ccb26

Please sign in to comment.