rsnext/packages/next/server/web/sandbox/sandbox.ts
Gal Schlezinger e69500462d
middlewares: limit process.env to inferred usage (#33186)
Production middlewares will only expose env vars that are statically analyzable, as mentioned here: https://nextjs.org/docs/api-reference/next/server#how-do-i-access-environment-variables

This creates some incompatibility with `next dev` and `next start`, where all `process.env` data is shared and can lead to unexpected behavior in runtime.

This PR fixes it by limiting the data in `process.env` with the inferred env vars from the code usage. I believe the test speaks for itself 🕺 

<!--
## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `yarn lint`
-->
2022-01-12 13:09:24 +00:00

39 lines
1 KiB
TypeScript

import type { RequestData, FetchEventResult } from '../types'
import { getModuleContext } from './context'
export async function run(params: {
name: string
env: string[]
onWarning: (warn: Error) => void
paths: string[]
request: RequestData
useCache: boolean
}): Promise<FetchEventResult> {
const { runInContext, context } = getModuleContext({
module: params.name,
onWarning: params.onWarning,
useCache: params.useCache !== false,
env: params.env,
})
for (const paramPath of params.paths) {
runInContext(paramPath)
}
const subreq = params.request.headers[`x-middleware-subrequest`]
const subrequests = typeof subreq === 'string' ? subreq.split(':') : []
if (subrequests.includes(params.name)) {
return {
waitUntil: Promise.resolve(),
response: new context.Response(null, {
headers: {
'x-middleware-next': '1',
},
}),
}
}
return context._ENTRIES[`middleware_${params.name}`].default({
request: params.request,
})
}