-
-
Notifications
You must be signed in to change notification settings - Fork 5k
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
Why is the SessionId always different when you send requests via useFetch? #27683
Comments
Start a new pull request in StackBlitz Codeflow. |
You would need to set the cookie returned by useFetch on the HTML response. This isn't done automatically right now, but we might consider doing it for useFetch. |
@danielroe thanks for the answer! But that doesn't work for me either. I created a composable fetchWithCookie and used it in my code. The sessionId is different every time. <script setup>
const event = useRequestEvent();
const { data } = await useAsyncData(() => fetchWithCookie(event, '/api/test'));
</script>
<template>
<div>
<p>
If you simply refresh the page, there will be a new session every time.
</p>
<pre>{{ data }}</pre>
<p>
But if you go straight to endpoint:
<a href="/api/test">/api/test</a>, the session id will be remain
permanent. Just what I need!
</p>
</div>
</template>
|
I solved my issue via middleware. And it’s strange, it doesn’t work in the endpoint, but works in the middleware. How can it be? /server/middleware/session.ts export default defineEventHandler(async (event) => {
console.log('middleware', {
sessionId: event.context.sessionsId,
cookie: getCookie(event, 'seesion-id-test-2'),
})
if (event.context.sessionsId) {
return
}
const session = await getSession(event, {
password: '80d42cfb-1cd2-462c-8f17-e3237d9027e9',
name: 'seesion-id-test-2',
cookie: {
maxAge: 3600,
path: '/',
sameSite: true,
},
})
event.context.sessionsId = session.id
}) |
every stranger how it work, with axios onRequest and onResponse great fine, or am I using it wrong? |
@leofredy |
I am also experiencing this problem. I am building a module for authentication, and need to use the session ID for caching. I'll see if I can show flow here. Module plugin: export default defineNuxtPlugin(async (nuxtApp) => {
const runtimeConfig = useRuntimeConfig().public.auth
const { getSession } = useAuth()
// Skip auth if we're prerendering
let nitroPrerender = false
if (nuxtApp.ssrContext) {
nitroPrerender = getHeader(nuxtApp.ssrContext.event, 'x-nitro-prerender') !== undefined
}
if (typeof data.value === 'undefined' && !nitroPrerender) {
if (import.meta.server) {
await getSession()
}
}
} useAuth get session function: const headers = await useRequestHeaders(['cookie']) //<-- This doesn't work because "A composable that requires access to the Nuxt instance was called outside of a plugin, Nuxt hook, Nuxt middleware, or Vue setup function."
console.log("🚀 ~ getSession ~ headers:", headers)
const response = await $fetch<SessionData>(path, {
headers: {
...headers,
Accept: 'text/json',
},
retry: false,
}).catch(() => ({})) useAuth get session function: const nuxt = useNuxtApp()
const headers = await callWithNuxt(nuxt, () => useRequestHeaders(['cookie'])) //<-- this 'works' but still changes the id
console.log("🚀 ~ getSession ~ headers:", headers)
const response = await $fetch<SessionData>(path, {
headers: {
...headers,
Accept: 'text/json',
},
retry: false,
}).catch(() => ({})) Example snippet from my auth redirect endpoint: export default defineEventHandler(async (event) => {
const body = await readBody(event)
if (!body || !body.state) {
throw createError({ status: 404, message: 'response not found' })
}
const session = await useSession<SessionSignInRequest>(event, {
password: useRuntimeConfig().session.password,
})
//... do sign in things ...
await session.update({
account: tokenResponse.account || undefined,
testSessionId: session.id, // <-- lets assume session.id = 1234
}) example get session endpoint: export default eventHandler(async (event) => {
try {
const session = await getUserPublicData(event)
return session
}
catch (error) {
return {}
}
})
export async function getUserPublicData(event: H3Event) {
const session = await useSession<SessionSignInRequest>(event, {
password: useRuntimeConfig().session.password,
})
console.log(session.id) //<--- From plugin calling getSession() would be 5678, but from middleware calling getSession would be 1234
consol.log(session.data.testSessionId) // <-- will be 1234
} Its very frustrating because it basically means I have to store the "correct" session ID along side the data, which isn't the end of the world, but something definitely isn't working right. I am going to try and build a demo repo to show the problem. |
Environment
Nuxt project info: (copied to clipboard) 11:00:46 AM
Reproduction
https://stackblitz.com/edit/github-mpxmop?file=app.vue,server%2Fapi%2Ftest%2Findex.ts
app.vue
/api/test/index.ts
Describe the bug
Hello Nuxt 3 team!
I apologize if this is not a bug, but my stupidity! :) I don't understand how I work in h3 with nuxt3.
If I send req through useFetch(), I get a different sessionId each time, but if I go directly to endpoint the session is fixed permanently sessionId. How can I get the same sessionId on the server side all the time if useFetch is going to be called all the time?
Cookies with a name "seesion-id-test" and a hash sometimes appear, sometimes they don’t.
Thank you for your attention!
Additional context
No response
Logs
No response
The text was updated successfully, but these errors were encountered: