Timkor/nuxt-session

where can I use session variable?

Opened this issue · 5 comments

Hi dear staff of this tool

  1. can you please tell, the session variable can be used in another places like Mounted?

  2. session variable can only be used in nuxtServerInit? how can I use it in another actions since another actions does not have req param?

  3. do you have examples? that would have great since this kind of tools really lacks of examples or tutorials in internet

thanks

Hi dextherry,

Yes you could use the session data everywhere you would like.

In order to do this, you could best make a Vuex store for the session data:

store/index.js

export const state = () => ({
  session: {}
})

export const mutations = {
    setSession(state, session) {
        state.session = session;
    }
}

export const actions = {
    
    async nuxtServerInit({dispatch, commit}, {req}) {

        // Get session ID:
        const sessionId = req.session.id;

        // Or set initial session state:
        if (req.session) {
            commit('setSessionData', req.session);
        }
    }
}

This way you can access the session data using Vuex getters nearly anywhere like in components and plugins.

But I would make a different module: store/session.js though.

You could also add server middleware, here you could access and alter the req.session object directly.

OH, thanks, I understand now how to get session data, just a question please, then, how can I save data in the session object? I mean the session variable that comes from req, (not the state session)
I tried setting a state and using it within a middleware like this, but it did not work

export default function ({store},req, res, next) {
req.session.somesessiondata = store.state.somestate;
next();
}

maybe it is possible to set a data in the session variable directly without using states?
help me with that please
Regards

@dextherry
You do not have access to the store in server middleware. But you can access the session object though.
I would make an API call using server middleware if I were you. You can alter the session object within the API call and use the response to alter the store on the client.

oh, I understand, thanks for your patience :)

@dextherry
You do not have access to the store in server middleware. But you can access the session object though.
I would make an API call using server middleware if I were you. You can alter the session object within the API call and use the response to alter the store on the client.

Can you give me an idea like what can i do to set the session so i could be able to retrieve info from it?