NuxtN
Nuxt14mo ago
Nisthar

Does plugins run after server middlewares?

I have a module plugin like

plugin.ts
:

import { defineNuxtPlugin, useRuntimeConfig } from '#app'

export default defineNuxtPlugin(async (nuxtApp) => {
  
  const config = useRuntimeConfig();
  const { fetchUser } = useAuth();
  const { token, checkAutoRefresh } = useToken();
  const user = useUser();

  async function checkIfUserExists() {
      if (!user.value && token.value) {
        await fetchUser();
      }
  }

  // do the checks server-side, instead of using hook 'app:created', 
  // as this hook is not called on SSR=true (static generation)
  await checkAutoRefresh();
  await checkIfUserExists();

  nuxtApp.hook('page:start', async () => {
    if (import.meta.client) {
      await checkAutoRefresh();
      await checkIfUserExists();
    }
  })
})


The plugin checks if the token is expired and refreshes it on the SSR. I am trying to get the refreshed token in the server middleware so i can fetch the currently logged in user in the server. But it seems like the server middlewares are run first before the plugin ever runs.

I need to use plugin to make the SSR auth work.

How do i get the refreshed token in the middleware so i can fetch for the user?
Was this page helpful?