Unverified Commit 1bf02661 authored by Michal Jez's avatar Michal Jez Committed by GitHub

Support custom servers with minimal node modules (#72966)

## Fixing a bug

### Related issues

fixes #64031

### Why is this change needed

Per the Next.js
[docs](https://nextjs.org/docs/pages/api-reference/next-config-js/output)

> Next.js' production server is also traced for its needed files and
output at .next/next-server.js.nft.json which can be leveraged in
production.

When I tried doing this my [custom
server](https://nextjs.org/docs/pages/building-your-application/configuring/custom-server)
would crash on startup because of this codepath


https://github.com/vercel/next.js/blob/canary/packages/next/src/server/config.ts#L1022

My first attempt at fixing this involved changing

```
if (!process.env.__NEXT_PRIVATE_STANDALONE_CONFIG) {
```

to

```
if (phase === PHASE_PRODUCTION_SERVER) {
```

but this is not guaranteed to work because the next.config.js and it's
required dependencies may not be present causing the server to use the
default config

The best solution is to mimic standalone mode as closely as possible

### What does this change do

This change allows a custom server running in production with only
required files to pass in a preloaded next config (most likely from
`required-server-files.json`)

This is very similar to how the [standalone server
works](https://github.com/vercel/next.js/blob/bc49287063d6afd50a7361566b14f1ab6c26b136/packages/next/src/build/utils.ts#L2142)

### Testing

I'd like to get an initial round of feedback from the next team before I
dive into writing an integration test. I patched nextjs in my repo and
this solution worked
parent e06bdce3
...@@ -87,16 +87,17 @@ const app = next({}) ...@@ -87,16 +87,17 @@ const app = next({})
The above `next` import is a function that receives an object with the following options: The above `next` import is a function that receives an object with the following options:
| Option | Type | Description | | Option | Type | Description |
| ------------ | ------------------ | ----------------------------------------------------------------------------------- | | ----------------- | -------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `conf` | `Object` | The same object you would use in `next.config.js`. Defaults to `{}` | | `conf` | `Object` | The same object you would use in `next.config.js`. Defaults to `{}` |
| `dev` | `Boolean` | (_Optional_) Whether or not to launch Next.js in dev mode. Defaults to `false` | | `dev` | `Boolean` | (_Optional_) Whether or not to launch Next.js in dev mode. Defaults to `false` |
| `dir` | `String` | (_Optional_) Location of the Next.js project. Defaults to `'.'` | | `dir` | `String` | (_Optional_) Location of the Next.js project. Defaults to `'.'` |
| `quiet` | `Boolean` | (_Optional_) Hide error messages containing server information. Defaults to `false` | | `quiet` | `Boolean` | (_Optional_) Hide error messages containing server information. Defaults to `false` |
| `hostname` | `String` | (_Optional_) The hostname the server is running behind | | `hostname` | `String` | (_Optional_) The hostname the server is running behind |
| `port` | `Number` | (_Optional_) The port the server is running behind | | `port` | `Number` | (_Optional_) The port the server is running behind |
| `httpServer` | `node:http#Server` | (_Optional_) The HTTP Server that Next.js is running behind | | `httpServer` | `node:http#Server` | (_Optional_) The HTTP Server that Next.js is running behind |
| `turbo` | `Boolean` | (_Optional_) Enable Turbopack | | `turbo` | `Boolean` | (_Optional_) Enable Turbopack |
| `preloadedConfig` | `NextConfigComplete` | (_Optional_) A preloaded config to be used instead of loading from `next.config.js`. Only works when `dev` is `false` |
The returned `app` can then be used to let Next.js handle requests as required. The returned `app` can then be used to let Next.js handle requests as required.
......
...@@ -25,6 +25,7 @@ import { getTracer } from './lib/trace/tracer' ...@@ -25,6 +25,7 @@ import { getTracer } from './lib/trace/tracer'
import { NextServerSpan } from './lib/trace/constants' import { NextServerSpan } from './lib/trace/constants'
import { formatUrl } from '../shared/lib/router/utils/format-url' import { formatUrl } from '../shared/lib/router/utils/format-url'
import type { ServerFields } from './lib/router-utils/setup-dev-bundler' import type { ServerFields } from './lib/router-utils/setup-dev-bundler'
import type { NextConfigComplete } from './config-shared'
let ServerImpl: typeof Server let ServerImpl: typeof Server
...@@ -40,7 +41,9 @@ export type NextServerOptions = Omit< ...@@ -40,7 +41,9 @@ export type NextServerOptions = Omit<
// This is assigned in this server abstraction. // This is assigned in this server abstraction.
'conf' 'conf'
> & > &
Partial<Pick<ServerOptions | DevServerOptions, 'conf'>> Partial<Pick<ServerOptions | DevServerOptions, 'conf'>> & {
preloadedConfig?: NextConfigComplete
}
export interface RequestHandler { export interface RequestHandler {
( (
...@@ -66,6 +69,18 @@ export class NextServer { ...@@ -66,6 +69,18 @@ export class NextServer {
constructor(options: NextServerOptions) { constructor(options: NextServerOptions) {
this.options = options this.options = options
// If we're in production mode and have a config that can be preloaded (from `next build`) then it's
// possible the server is running in an environment similar to standalone mode where only required node
// modules are present. Without setting the following environment variable multiple things can happen:
// - The server will crash on startup from `loadWebpackConfig` in `loadConfig` because the files
// are not available
// - The server will load an incorrect config because the `next.config.js` file is not available
if (!this.options.dev && this.options.preloadedConfig) {
process.env.__NEXT_PRIVATE_STANDALONE_CONFIG = JSON.stringify(
this.options.preloadedConfig
)
}
} }
get hostname() { get hostname() {
...@@ -389,6 +404,12 @@ function createServer( ...@@ -389,6 +404,12 @@ function createServer(
) )
} }
if (options.dev && options.preloadedConfig) {
log.warn(
'`dev` is set to true but `preloadedConfig` is provided. `preloadedConfig` will be ignored.'
)
}
// When the caller is a custom server (using next()). // When the caller is a custom server (using next()).
if (options.customServer !== false) { if (options.customServer !== false) {
const dir = resolve(options.dir || '.') const dir = resolve(options.dir || '.')
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment