Use Session in Nuxt Store nuxtServerInit


#1

Hi.
I want to implement Auth routes in Nuxt according to their example here but using Adonis file session.

This is using server side session info and pass it to the Vue Store so it can be used in the front-end.

In the example they use express session and they can use it at the store.js file calling context.req.session.
They can do that because on server.js they put this lines:

// Sessions to create `req.session`
app.use(session({
  secret: 'super-secret-key',
  resave: false,
  saveUninitialized: false,
  cookie: { maxAge: 60000 }
}))

This is my root/start/server.js:

const cluster = require('cluster')

if (cluster.isMaster) {
  for (let i=0; i < 4; i ++) {
    cluster.fork()
  }
  require('@adonisjs/websocket/clusterPubSub')()
  return
}

const { Ignitor } = require('@adonisjs/ignitor')
new Ignitor(require('@adonisjs/fold'))
 .appRoot(__dirname)
 .wsServer()
 .fireHttpServer(
  use('App/Controllers/Http/NuxtController')
 )
 .catch(console.error)

How can I get to use Adonis Session in the Store nuxtServerInit()?

Thanks.


#2

Hey @jorgeyoma! :wave:

Should be pretty simple.

First, your Adonis controller should act like nothing special will happen, use the auth.attempt() method.

Then your nuxtServerInit() method should look like this.

async nuxtServerInit ({ dispatch }, { app }) {
  try {
    await dispatch('getCurrentUser')
  } catch (e) {}
},

My method getCurrentUser will simply try to fetch the authenticated user.

async getCurrentUser ({ commit }) {
  try {
    const user = await this.$axios.$get('me')
    commit('SET_AUTHENTICATE_USER', user)
  } catch (e) {
    throw e
  }
},

#3

Hi @romain.lanz .
I tested your solution and I’m having problems with the Adonis Sessions. The session doesn’t persist after a refresh of the page, so neither sessions and auth are working with NuxtServerInit as the response is null. I posted another topic with the issue.


#4

Hi @romain.lanz.

I can’t find the problem with NUXT and Adonis Sessions. Below you can find the issue I posted in NUXT, I haven’t receive any help.

I changed the session config of the nuxt-create-app to sameSite = false. With this when I send a REST request via Chrome Postman the session persist, but the session doesn’t persist when I use it with Nuxt and I do a refresh.

cookie: {
    httpOnly: true,
    sameSite: false,
    path: '/'
  },

As yet there is no way to use Vuex persist in a fluent way with NUXT, Sessions is the only way to go to get Auth working.

Please take a look at it.

Nuxt CMTY issue


#5

Do you use AdoNuxt or is it your custom Nuxt app, living inside Adonis?


#6

Hi @virk

I’m using nuxt-create-app from nuxt.org to create the app.

in this link you can find the steps to reproduce it.

nuxt adonis session problem

I tryied to use vuex with jwt as alternative but vuex doesn’t persist well with nuxt.