nuxt-community / express-template

Starter template for Nuxt 2 with Express.
https://codesandbox.io/s/github/nuxt-community/express-template
1.25k stars 239 forks source link

How to use express-session with new serverMiddleware approach? #198

Closed SnitchRUS66 closed 3 years ago

SnitchRUS66 commented 3 years ago

How to use express-session with new serverMiddleware approach? When I call req.session in nuxtServerInit it is undefined.

atinux commented 3 years ago

Can you give an example please? Basically you simply need to add the express-session here: https://github.com/nuxt-community/express-template/blob/master/api/index.js#L5

SnitchRUS66 commented 3 years ago

Yes, that's what I did. After 6 hours of experimenting, I came up with success. If register middleware as

serverMiddleware: {
    '/api': '~/index'
},

It turns out that the req.session is undefined in nuxtServerInit. But if register middleware as

serverMiddleware: [
    '~/index'
],

It starts work correctly. Maybe I misunderstand something? This issue also related to https://github.com/nuxt/nuxt.js/issues/5119

atinux commented 3 years ago

Ok so the point is that you want to use req.session in nuxtServerInit, so yes you can do this.

You can also do:

serverMiddleware: [
  require('express-session')(/* options */)
]
Coinhexa commented 2 years ago

What happens if nuxt is on the frontend at localhost:3000 and express is a separate backend at localhost:8000 with express-session, how does it work there

yfliao90 commented 1 year ago

Yes, that's what I did. After 6 hours of experimenting, I came up with success. If register middleware as

serverMiddleware: {
    '/api': '~/index'
},

It turns out that the req.session is undefined in nuxtServerInit. But if register middleware as

serverMiddleware: [
    '~/index'
],

It starts work correctly. Maybe I misunderstand something? This issue also related to nuxt/nuxt#5119

Thanks to your answer I finally struggled out my problem.

I guess

serverMiddleware: [ '~/index' ],

means

serverMiddleware: [ { path : '/', handler: '~/index'} ],

Only if this express-session server middleware applied to whole routes will it work.