Skip to content

fix: prevent Next from defining duplicate global property in edge functions #1682

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions cypress/integration/middleware/standard.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,11 @@ describe('Middleware matchers', () => {
})
})
})

describe('Middleware with edge API', () => {
it('serves API routes from the edge runtime', () => {
cy.request('/api/edge').then((response) => {
expect(response.body).to.include('Hello world')
})
})
})
5 changes: 5 additions & 0 deletions demos/middleware/pages/api/edge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export const config = {
runtime: 'experimental-edge',
}

export default (req) => new Response('Hello world!')
28 changes: 19 additions & 9 deletions packages/runtime/src/helpers/edge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,14 +71,21 @@ const sanitizeName = (name: string) => `next_${name.replace(/\W/g, '_')}`
/**
* Initialization added to the top of the edge function bundle
*/
const bootstrap = /* js */ `
const preamble = /* js */ `

globalThis.process = { env: {...Deno.env.toObject(), NEXT_RUNTIME: 'edge', 'NEXT_PRIVATE_MINIMAL_MODE': '1' } }
globalThis._ENTRIES ||= {}
let _ENTRIES = {}
// Deno defines "window", but naughty libraries think this means it's a browser
delete globalThis.window

// Next uses "self" as a function-scoped global-like object
const self = {}
`

// Slightly different spacing in different versions!
const IMPORT_UNSUPPORTED = [
`Object.defineProperty(globalThis,"__import_unsupported"`,
` Object.defineProperty(globalThis, "__import_unsupported"`,
]
/**
* Concatenates the Next edge function code with the required chunks and adds an export
*/
Expand All @@ -90,17 +97,20 @@ const getMiddlewareBundle = async ({
netlifyConfig: NetlifyConfig
}): Promise<string> => {
const { publish } = netlifyConfig.build
const chunks: Array<string> = [bootstrap]
const chunks: Array<string> = [preamble]
for (const file of edgeFunctionDefinition.files) {
const filePath = join(publish, file)
const data = await fs.readFile(filePath, 'utf8')

let data = await fs.readFile(filePath, 'utf8')
// Next defines an immutable global variable, which is fine unless you have more than one in the bundle
// This adds a check to see if the global is already defined
data = IMPORT_UNSUPPORTED.reduce(
(acc, val) => acc.replace(val, `('__import_unsupported' in globalThis)||${val}`),
data,
)
chunks.push('{', data, '}')
}

const middleware = await fs.readFile(join(publish, `server`, `${edgeFunctionDefinition.name}.js`), 'utf8')

chunks.push(middleware)

Comment on lines -100 to -103
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't needed anymore, because the middleware file itself is included in edgeFunctionDefinition.files

const exports = /* js */ `export default _ENTRIES["middleware_${edgeFunctionDefinition.name}"].default;`
chunks.push(exports)
return chunks.join('\n')
Expand Down