rsnext/packages/next/server/dev/static-paths-worker.ts
Javi Velasco 85cc454023
Add port and hostname options to Next Server (#31858)
A middleware can work as a proxy intercepting requests and then performing a `fetch` to the destination adding headers to the request / response as a "man in the middle". When using `fetch` from a middleware we are not in the context of a browser so we can't really use relative URLs, they must be always absolute.

Now consider the previous case when middleware is running in *server mode*. Typically in order to know the host where we are fetching we can use the `request.nextUrl` which is given to the middleware but in this case the invoker (which is next-server) has no context of the hostname, nor the port. To solve this use case we must make the invoker of the middleware aware of the origin hostname and port.

This PR: 

- Introduces `hostname` and `port` as options for `NextServer`.
- Refactors types in `NextServer` and `NextDevServer` moving type only imports to the top of the file.
- Refactors `startServer` to do a best guess on the `hostname` and `port`, passing them down.
- Exposes `.port` and `.hostname` to be retrieved from the `app`.

In an upcoming PR we will pass the host guess to the middleware to solve the relative URL issue.
2021-11-28 16:48:43 +00:00

59 lines
1.6 KiB
TypeScript

import type { GetStaticPaths } from 'next/types'
import type { NextConfigComplete } from '../config-shared'
import type { UnwrapPromise } from '../../lib/coalesced-function'
import '../node-polyfill-fetch'
import { buildStaticPaths } from '../../build/utils'
import { loadComponents } from '../load-components'
import { setHttpAgentOptions } from '../config'
type RuntimeConfig = any
let workerWasUsed = false
// we call getStaticPaths in a separate process to ensure
// side-effects aren't relied on in dev that will break
// during a production build
export async function loadStaticPaths(
distDir: string,
pathname: string,
serverless: boolean,
config: RuntimeConfig,
httpAgentOptions: NextConfigComplete['httpAgentOptions'],
locales?: string[],
defaultLocale?: string
): Promise<
Omit<UnwrapPromise<ReturnType<GetStaticPaths>>, 'paths'> & {
paths: string[]
encodedPaths: string[]
}
> {
// we only want to use each worker once to prevent any invalid
// caches
if (workerWasUsed) {
process.exit(1)
}
// update work memory runtime-config
require('../../shared/lib/runtime-config').setConfig(config)
setHttpAgentOptions(httpAgentOptions)
const components = await loadComponents(distDir, pathname, serverless)
if (!components.getStaticPaths) {
// we shouldn't get to this point since the worker should
// only be called for SSG pages with getStaticPaths
throw new Error(
`Invariant: failed to load page with getStaticPaths for ${pathname}`
)
}
workerWasUsed = true
return buildStaticPaths(
pathname,
components.getStaticPaths,
config.configFileName,
locales,
defaultLocale
)
}