nuxt-community / express-template

Starter template for Nuxt 2 with Express.

Home Page:https://codesandbox.io/s/github/nuxt-community/express-template

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to use express-session with new serverMiddleware approach?

SnitchRUS66 opened this issue · comments

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

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

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

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 */)
]

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

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.