Skip to content

Implement nuxtServerInit Action to load data from server-side on the initial load #1080

Open
@MarceloLuis1997

Description

@MarceloLuis1997

What problem is this solving

Implement something like NuxtServerInit Action, so we can load data from the server-side and give it directly to the client-side on the initial load/render.

Proposed solution

Include an index.js file inside /stores with a nuxtServerInit action which will be called from the server-side on the initial load.

Describe alternatives you've considered

The only way I found to do this is using Pinia with Vuex, using the nuxtServerInit from Vuex:

// store/index.js
import { useSessionStore } from '~/stores/session'

export const actions = {
  async nuxtServerInit ({ dispatch }, { req, redirect, $pinia }) {
    if (!req.url.includes('/auth/')) {
      const store = useSessionStore($pinia)

      try {
        await store.me() // load user information from the server-side before rendering on client-side
      } catch (e) {
        redirect('/auth/login') // redirects to login if user is not logged in
      }
    }
  }
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions