@mintlify/previewing
Version:
Preview Mintlify docs locally
44 lines (43 loc) • 2.51 kB
JavaScript
import fse from 'fs-extra';
import { pathToFileURL } from 'node:url';
import { CLIENT_PATH, NEXT_CONFIG_PATH, NEXT_ROUTER_SERVER_PATH, NEXT_SIDE_EFFECT_PATH, } from '../constants.js';
/**
* When creating a standalone build, next.js outputs a server.js file that can be used as
* an entry point into the server. However, because we want to customize some parts of the
* http server (adding a socket.io server, serving the whole public directory), we
* create the server ourselves, and just reproduce the setup that next.js would do.
*
* Because we need to directly import from node_modules files, this solution seems very hacky,
* but it is arguably no more hacky than using the server.js that ships with the standalone
* build.
*
* This function attempts to replicate the behavior of two next.js files:
* - environment setup from server.js
* - initialization of the request handler from start-server.ts
*
* Links:
* - [standalone build](https://nextjs.org/docs/pages/api-reference/next-config-js/output#automatically-copying-traced-files)
* - [server.js](https://github.com/vercel/next.js/blob/492156b4c5e2559b2a280f7d483cd85a8e8742a9/packages/next/src/build/utils.ts#L2108-L2113) (created programmatically)
* - [start-server.ts](https://github.com/vercel/next.js/blob/59e5ccb225189d366f57f1b204c5f44053a434ce/packages/next/src/server/lib/start-server.ts#L416-L429)
*
* @returns the request handler provided by next.js
*/
export const setupNext = async () => {
const hostname = process.env.HOSTNAME || 'localhost';
const { config } = await JSON.parse(fse.readFileSync(NEXT_CONFIG_PATH, 'utf8'));
process.env.__NEXT_PRIVATE_STANDALONE_CONFIG = JSON.stringify(config);
// The server.js provided by next.js's standalone build does a similar import of this file.
// Not sure what side effects are being created, but want to change as little as possible.
// Also, Windows requires us to use `pathToFileURL` (see #899)
await import(pathToFileURL(NEXT_SIDE_EFFECT_PATH).href);
const { initialize } = await import(pathToFileURL(NEXT_ROUTER_SERVER_PATH).href);
// requestHandler was returned as an array in Next 14, and as an object in Next 15
// this lets us support both version for old (<=0.0.1326) and new (>=0.0.1327) versions of the client app
const result = await initialize({
dir: CLIENT_PATH,
dev: false,
hostname,
minimalMode: true,
});
return Array.isArray(result) ? result[0] : result.requestHandler;
};