Skip to content

Commit

Permalink
fix: add useAPIMiddleware flag and enable by default
Browse files Browse the repository at this point in the history
  • Loading branch information
brandonroberts committed Oct 2, 2024
1 parent 650f4a7 commit b99e9de
Show file tree
Hide file tree
Showing 6 changed files with 103 additions and 8 deletions.
6 changes: 6 additions & 0 deletions packages/platform/src/lib/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,12 @@ export interface Options {
* Additional files to include in compilation
*/
include?: string[];
/**
* Toggles internal API middleware.
* If disabled, a proxy request is used to route /api
* requests to / in the production server build.
*/
useAPIMiddleware?: boolean;
}

export interface PrerenderContentDir {
Expand Down
7 changes: 7 additions & 0 deletions packages/vite-plugin-nitro/src/lib/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ export interface Options {
*/
additionalAPIDirs?: string[];
apiPrefix?: string;

/**
* Toggles internal API middleware.
* If disabled, a proxy request is used to route /api
* requests to / in the production server build.
*/
useAPIMiddleware?: boolean;
}

export interface PrerenderOptions {
Expand Down
27 changes: 27 additions & 0 deletions packages/vite-plugin-nitro/src/lib/runtime/api-middleware.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* This file is shipped as ESM for Windows support,
* as it won't resolve the api-middleware.ts file correctly in node.
*/
import { eventHandler, proxyRequest } from 'h3';

export default eventHandler(async (event) => {
// @ts-ignore
const apiPrefix = `/${import.meta.env?.RUNTIME_CONFIG?.apiPrefix ?? 'api'}`;
if (event.node.req.url?.startsWith(apiPrefix)) {
const reqUrl = event.node.req.url?.replace(apiPrefix, '');

if (
event.node.req.method === 'GET' &&
// in the case of XML routes, we want to proxy the request so that nitro gets the correct headers
// and can render the XML correctly as a static asset
!event.node.req.url?.endsWith('.xml')
) {
return $fetch(reqUrl, { headers: event.node.req.headers });
}

return proxyRequest(event, reqUrl, {
// @ts-ignore
fetch: $fetch.native,
});
}
});
26 changes: 26 additions & 0 deletions packages/vite-plugin-nitro/src/lib/runtime/api-middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { eventHandler, proxyRequest } from 'h3';

export default eventHandler(async (event) => {
// @ts-ignore
const apiPrefix = `/${import.meta.env.RUNTIME_CONFIG?.apiPrefix ?? 'api'}`;
if (event.node.req.url?.startsWith(apiPrefix)) {
const reqUrl = event.node.req.url?.replace(apiPrefix, '');

if (
event.node.req.method === 'GET' &&
// in the case of XML routes, we want to proxy the request so that nitro gets the correct headers
// and can render the XML correctly as a static asset
!event.node.req.url?.endsWith('.xml')
) {
return $fetch(reqUrl, {
headers: event.node.req.headers,
context: event.context,
});
}

return proxyRequest(event, reqUrl, {
// @ts-ignore
fetch: $fetch.native,
});
}
});
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,7 @@ export const mockNitroConfig: NitroConfig = {
},
],
},
routeRules: {
'/api/**': { proxy: { to: '/**' } },
},
routeRules: undefined,
};

export async function mockBuildFunctions() {
Expand Down
41 changes: 36 additions & 5 deletions packages/vite-plugin-nitro/src/lib/vite-plugin-nitro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ export function nitro(options?: Options, nitroOptions?: NitroConfig): Plugin[] {
const workspaceRoot = options?.workspaceRoot ?? process.cwd();
const isTest = process.env['NODE_ENV'] === 'test' || !!process.env['VITEST'];
const apiPrefix = `/${options?.apiPrefix || 'api'}`;
const useAPIMiddleware =
typeof options?.useAPIMiddleware !== 'undefined'
? options?.useAPIMiddleware
: true;

let isBuild = false;
let isServe = false;
Expand Down Expand Up @@ -58,6 +62,11 @@ export function nitro(options?: Options, nitroOptions?: NitroConfig): Plugin[] {
additionalPagesDirs: options?.additionalPagesDirs,
});

const apiMiddlewareHandler =
filePrefix +
normalizePath(
join(__dirname, `runtime/api-middleware${filePrefix ? '.mjs' : ''}`)
);
const ssrEntry = normalizePath(
filePrefix +
resolve(
Expand Down Expand Up @@ -114,10 +123,22 @@ export function nitro(options?: Options, nitroOptions?: NitroConfig): Plugin[] {
},
plugins: [pageEndpointsPlugin()],
},
handlers: [...pageHandlers],
routeRules: {
[`${apiPrefix}/**`]: { proxy: { to: '/**' } },
},
handlers: [
...(useAPIMiddleware
? [
{
handler: apiMiddlewareHandler,
middleware: true,
},
]
: []),
...pageHandlers,
],
routeRules: useAPIMiddleware
? undefined
: {
[`${apiPrefix}/**`]: { proxy: { to: '/**' } },
},
};

if (isVercelPreset(buildPreset)) {
Expand Down Expand Up @@ -251,7 +272,17 @@ export function nitro(options?: Options, nitroOptions?: NitroConfig): Plugin[] {
external: ['rxjs', 'node-fetch-native/dist/polyfill'],
},
moduleSideEffects: ['zone.js/node', 'zone.js/fesm2015/zone-node'],
handlers: [...pageHandlers],
handlers: [
...(useAPIMiddleware
? [
{
handler: apiMiddlewareHandler,
middleware: true,
},
]
: []),
...pageHandlers,
],
};
}
}
Expand Down

0 comments on commit b99e9de

Please sign in to comment.