Skip to content

Commit

Permalink
fix: cookie being reset on reload in ssg build (#3087)
Browse files Browse the repository at this point in the history
* fix: cookie being reset on reload in ssg build

* test: assert ssg cookie not being reset
  • Loading branch information
BobbieGoede committed Sep 5, 2024
1 parent 9e91653 commit 7ccaf16
Show file tree
Hide file tree
Showing 5 changed files with 62 additions and 21 deletions.
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(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 @@ -159,6 +159,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', () => {
__DEBUG__ && console.log('hook app:mounted')
const detected = detectBrowserLanguage(
Expand All @@ -167,7 +168,7 @@ export default defineNuxtPlugin({
ssg: 'ssg_setup',
callType: 'setup',
firstAccess: true,
localeCookie: _getLocaleCookie(localeCookie, _detectBrowserLanguage, runtimeI18n.defaultLocale)
localeCookie: initialLocaleCookie
},
initialLocale
)
Expand Down

0 comments on commit 7ccaf16

Please sign in to comment.