Skip to content
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

feat(ssr): When available, leave process.env. accessible in SSR #4192

Closed
wants to merge 3 commits into from
Closed
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
9 changes: 9 additions & 0 deletions packages/playground/ssr-react/__tests__/ssr-react.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,15 @@ import fetch from 'node-fetch'

const url = `http://localhost:${port}`

test('/env', async () => {
await page.goto(url + '/env')
expect(await page.textContent('h1')).toMatch('default message here')

// raw http request
const envHtml = await (await fetch(url + '/env')).text()
expect(envHtml).toMatch('API_KEY_qwertyuiop')
})

test('/about', async () => {
await page.goto(url + '/about')
expect(await page.textContent('h1')).toMatch('About')
Expand Down
2 changes: 2 additions & 0 deletions packages/playground/ssr-react/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ const express = require('express')

const isTest = process.env.NODE_ENV === 'test' || !!process.env.VITE_TEST_BUILD

process.env.MY_CUSTOM_SECRET = 'API_KEY_qwertyuiop'

async function createServer(
root = process.cwd(),
isProd = process.env.NODE_ENV === 'production'
Expand Down
7 changes: 7 additions & 0 deletions packages/playground/ssr-react/src/pages/Env.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export default function Env() {
let msg = 'default message here';
try {
msg = process.env.MY_CUSTOM_SECRET || msg;
} catch {}
return <h1>{msg}</h1>
}
71 changes: 48 additions & 23 deletions packages/vite/src/node/plugins/define.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,31 +30,54 @@ export function definePlugin(config: ResolvedConfig): Plugin {
})
}

const replacements: Record<string, string | undefined> = {
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV || config.mode),
'global.process.env.NODE_ENV': JSON.stringify(
process.env.NODE_ENV || config.mode
),
'globalThis.process.env.NODE_ENV': JSON.stringify(
process.env.NODE_ENV || config.mode
),
...userDefine,
...importMetaKeys,
'process.env.': `({}).`,
'global.process.env.': `({}).`,
'globalThis.process.env.': `({}).`
function generatePattern(
ssr: boolean
): [Record<string, string | undefined>, RegExp] {
const processEnv = ssr
? {
// account for non-node environments like v8
'process.env.': `(typeof process === 'undefined' ? {} : process.env).`,
'global.process.env.': `(typeof global.process === 'undefined' ? {} : global.process.env).`,
'globalThis.process.env.': `(typeof globalThis.process === 'undefined' ? {} : globalThis.process.env).`
}
Comment on lines +36 to +42
Copy link
Member Author

Choose a reason for hiding this comment

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

I'm extremely unhappy with this runtime check, but as @frandiox points out, potential target environments like Cloudflare Workers and Deno Deploy do not have process as it is a node-ism.

Information about the target environment would need to be available at build time in order to remove the runtime check.

Copy link
Contributor

@frandiox frandiox Jul 9, 2021

Choose a reason for hiding this comment

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

@GrygrFlzr I believe there's a build variable in Vite, ssr.target, which you might be able to use for this. It can have webworker value. Therefore, the check would happen at build-time instead of run-time like in this code 🤔

Not sure if it's easy to access that variable though.

#3151

: {
// client never has process
'process.env.': `({}).`,
'global.process.env.': `({}).`,
'globalThis.process.env.': `({}).`
}

const replacements: Record<string, string | undefined> = {
'process.env.NODE_ENV': JSON.stringify(
process.env.NODE_ENV || config.mode
),
'global.process.env.NODE_ENV': JSON.stringify(
process.env.NODE_ENV || config.mode
),
'globalThis.process.env.NODE_ENV': JSON.stringify(
process.env.NODE_ENV || config.mode
),
...userDefine,
...importMetaKeys,
...processEnv
}

const pattern = new RegExp(
'(?<!\\.)\\b(' +
Object.keys(replacements)
.map((str) => {
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&')
})
.join('|') +
')\\b',
'g'
)

return [replacements, pattern]
}

const pattern = new RegExp(
'(?<!\\.)\\b(' +
Object.keys(replacements)
.map((str) => {
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&')
})
.join('|') +
')\\b',
'g'
)
const defaultPattern = generatePattern(false)
const ssrPattern = generatePattern(true)

return {
name: 'vite:define',
Expand All @@ -73,6 +96,8 @@ export function definePlugin(config: ResolvedConfig): Plugin {
return
}

const [replacements, pattern] = ssr ? ssrPattern : defaultPattern

if (ssr && !isBuild) {
// ssr + dev, simple replace
return code.replace(pattern, (_, match) => {
Expand Down