Add session support in Nuxt.js, accessible in server middleware using express and express-session
- Add
nuxt-session
dependency using npm to your project:
npm install nuxt-session
- Add
nuxt-session
tomodules
section ofnuxt.config.js
:
{
modules: ['nuxt-session'],
}
Note that if you do not use express
and express-session
already:
npm install express express-session
module.exports = (req, res, next) => {
// Get the session ID:
console.log(req.session.id);
// Assign some value to session:
req.session.someKey = 'some value';
// Get some value:
const someOtherValue = req.session.someOtherKey;
next();
}
The session
object will automatically be injected into the context of nuxt-api
.
File /server/api/cart/add.js
:
export default {
method: 'POST',
params: {
productId: {
type: String,
required: true
}
},
call({productId}, {session}) {
if (!session.cart) {
session.cart = [];
}
session.cart.push(productId);
return session.cart;
}
};
File /store/index.js
:
export const actions = {
async nuxtServerInit({dispatch, commit}, {req}) {
// Get session ID:
const sessionId = req.session.id;
// Or set initial cart state:
if (session && session.cart) {
dispatch('cart/setProducts', session.cart);
}
}
};
Pass the express-session options directly into this module:
{
modules: [
[
'nuxt-session',
{
// express-session options:
name: 'nuxt-session-id',
secret: 'some secret key'
}
],
],
}
For some session stores you will need the express session object. You can get it by passing the options as as function:
{
modules: [
[
'nuxt-session',
(session) => {
// Use the session object:
var RedisStore = require('connect-redis')(session);
return {
name: 'sessionId',
store: new RedisStore({
host: 'localhost',
port: '1234'
}),
secret: 'some secret key',
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 7 * 52 * 2 // 2 years
},
saveUninitialized: true,
resave: false
};
],
],
}