sidebase / nuxt-session

Nuxt session middleware to get a persistent session per app user, e.g., to store data across multiple requests. The nuxt session module provides the useSession() composable out of the box and sets up API endpoints to interact with your session to make working with sessions feel like a breeze.
https://sidebase.io/nuxt-session/
MIT License
189 stars 21 forks source link

Single session per application #65

Closed Darkside73 closed 1 year ago

Darkside73 commented 1 year ago

Ask your question

After installing module I get different session ids (and essentially separate sessions) for each API request

// nuxt.config.ts
export default defineNuxtConfig({
  modules: [
    @sidebase/nuxt-session'
  ]
})
// server/api/foo.get.ts
export default eventHandler((event) => {
  console.log('/foo', event.context.session.id)
  return 'foo'
})

// server/api/bar.get.ts
export default eventHandler((event) => {
  console.log('/bar', event.context.session.id)
  return 'bar'
})
<script setup lang="ts">
const foo = await useFetch('/api/foo')
const bar = await useFetch('/api/bar')
</script>

<template>
  <div>
    {{ foo }}
    <br>
    {{ bar }}
  </div>
</template>

Server stdout

/foo ZwS1Mbg0mhwZ3Fr51uu0HueqW2QqN2ODvKPtr-nbMYfLvpA7UUm-_mjzP7yuELJb                                                                                                      
/bar vksnahk5IG8XfXo5B1LQbTFtUrtB8sjThpRM8r3CVuQLGJ4PMxH0Q0qe-dUq9Fz9  

Each request generates new session id. Is it possible achieve single session?

Additional information

No response

BananaAcid commented 1 year ago

All tests below work. If not in an iFrame BY DEFAULT - CodeSandbox: need to be opened in its own window to work.

This can be mitigated by changing the plugin's config (a note about it, should probably be added to readme):


export default defineNuxtConfig({
  modules: ["@sidebase/nuxt-session"],
  session: {
    session: {
      // allows to work in an iframe, and anywhere
      cookieSameSite: "none", // default is "lax"
      cookieSecure: true,
    },
  },
});

Tests:

let z = await fetch('/api/foo', {
  method: 'GET',
  credentials: 'include'
}).then(d => d.json());
console.log('/foo JSON', z);
let x  = await fetch('/api/session', {
  method: 'GET',
  credentials: 'include'
}).then(d => d.json())
console.log('SESSION JSON', x); // {id: ...
let y = await useFetch("/api/session");
console.log("/api/session 1", y.data.value.id);

y = await useFetch("/api/session");
console.log("/api/session 2", y.data.value.id);

testing here: https://codesandbox.io/p/sandbox/template-for-nuxt3-vue3-typescript-jsx-pug-less-sass-sessions-qttdx0

Darkside73 commented 1 year ago

Thanks. The issue was in outdated dependencies (nuxt itself I think)

BananaAcid commented 1 year ago

@Darkside73 How do you feel about This can be mitigated by changing the plugin's config (a note about it, should probably be added to readme): ?