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

fix: cookie being reset on reload in ssg build #3087

Merged
merged 2 commits into from
Sep 5, 2024
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
45 changes: 45 additions & 0 deletions specs/ssg/no_prefix.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { test, expect } from 'vitest'
import { fileURLToPath } from 'node:url'
import { setup } from '../utils'
import { getText, gotoPath, renderPage, startServerWithRuntimeConfig, waitForURL } from '../helper'

await setup({
rootDir: fileURLToPath(new URL(`../fixtures/basic`, import.meta.url)),
browser: true,
prerender: true,
// overrides
nuxtConfig: {
i18n: {
debug: true,
strategy: 'no_prefix',
detectBrowserLanguage: {
useCookie: true,
cookieKey: 'my_custom_cookie_name',
redirectOn: 'root',
cookieCrossOrigin: true,
cookieSecure: true
}
}
}
})

test('does not reset cookie no refresh', async () => {
const { page } = await renderPage('/', { locale: 'en' })
const ctx = await page.context()
expect(await ctx.cookies()).toMatchObject([
{ name: 'my_custom_cookie_name', value: 'en', secure: true, sameSite: 'None' }
])

// click `fr` lang switch link
await page.locator('#set-locale-link-fr').click()
expect(await ctx.cookies()).toMatchObject([
{ name: 'my_custom_cookie_name', value: 'fr', secure: true, sameSite: 'None' }
])

await page.reload()
await waitForURL(page, '/')

expect(await ctx.cookies()).toMatchObject([
{ name: 'my_custom_cookie_name', value: 'fr', secure: true, sameSite: 'None' }
])
})
2 changes: 1 addition & 1 deletion specs/utils/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export function createTestContext(options: Partial<TestOptions>): TestContext {
configFile: 'nuxt.config',
setupTimeout: 120 * 1000,
dev: !!JSON.parse(process.env.NUXT_TEST_DEV || 'false'),
prerender: false,
prerender: options.prerender ?? false,
logLevel: 1,
server: true,
build: options.browser !== false || options.server !== false,
Expand Down
8 changes: 4 additions & 4 deletions specs/utils/nuxt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,17 +59,17 @@ export async function loadFixture(testContext: VitestContext) {
let testKey = getTestKey(testContext)

const buildDir = resolve(ctx.options.rootDir, '.nuxt', testKey)
const outputDir = ctx.options.prerender
? resolve(buildDir, 'output', testKey)
: resolve(ctx.options.rootDir, '.output', testKey)
const outputDir = resolve(ctx.options.rootDir, '.output', testKey)

ctx.options.nuxtConfig = defu(ctx.options.nuxtConfig, {
buildDir,
// NOTE: the following code is added for prerender
_generate: ctx.options.prerender,
nitro: {
...(ctx.options.prerender ? { static: true } : {}),
output: {
dir: outputDir
dir: outputDir,
...(ctx.options.prerender ? { publicDir: outputDir + '/public' } : {})
}
}
})
Expand Down
25 changes: 10 additions & 15 deletions specs/utils/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,28 +49,23 @@ export async function startServer(env: Record<string, unknown> = {}) {
ctx.serverProcess.kill()
throw lastError || new Error('Timeout waiting for dev server!')
} else if (ctx.options.prerender) {
const command = `npx serve -s ./dist -p ${port}`
const command = `npx serve -s ${ctx.nuxt!.options.nitro!.output?.publicDir} -l tcp://${host}:${port} --no-port-switching`
// ; (await import('consola')).consola.restoreConsole()
const [_command, ...commandArgs] = command.split(' ')

ctx.serverProcess = execa(_command, commandArgs, {
cwd: ctx.nuxt!.options.rootDir,
//@ts-ignore
env: {
...process.env,
PORT: String(port),
HOST: host,
...env
}
// stdio: 'inherit'
})
await waitForPort(port, { retries: 32 })
for (let i = 0; i < 50; i++) {
await new Promise(resolve => setTimeout(resolve, 100))
try {
const res = await $fetch(ctx.nuxt!.options.app.baseURL)
if (!res.includes('__NUXT_LOADING__')) {
return
}
} catch {}
}
ctx.serverProcess.kill()
throw new Error('Timeout waiting for ssg preview!')

await waitForPort(port, { retries: 32, host, delay: 1000 })
} else {
//@ts-ignore
ctx.serverProcess = execa('node', [resolve(ctx.nuxt!.options.nitro.output!.dir!, 'server/index.mjs')], {
stdio: 'inherit',
env: {
Expand Down
3 changes: 2 additions & 1 deletion src/runtime/plugins/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ export default defineNuxtPlugin({
* avoid hydration mismatch for SSG mode
*/
if (isSSGModeInitialSetup() && runtimeI18n.strategy === 'no_prefix' && import.meta.client) {
const initialLocaleCookie = localeCookie.value
nuxt.hook('app:mounted', async () => {
__DEBUG__ && logger.log('hook app:mounted')
const detected = detectBrowserLanguage(
Expand All @@ -160,7 +161,7 @@ export default defineNuxtPlugin({
ssg: 'ssg_setup',
callType: 'setup',
firstAccess: true,
localeCookie: getLocaleCookie(localeCookie, _detectBrowserLanguage, runtimeI18n.defaultLocale)
localeCookie: initialLocaleCookie
},
initialLocale
)
Expand Down