question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[SSR Auth] res.locals is always an empty object / res.locals.user always undefined

See original GitHub issue

I’m getting the same problem as #134 but none of the solutions mentioned worked. I can’t get anything from res.locals, it’s always an empty object.

This is my nuxt.config.js

module.exports.default = {
  mode: "universal",
  /*
   ** Headers of the page
   */
  head: {
    title: process.env.npm_package_name || "",
    meta: [
      { charset: "utf-8" },
      { name: "viewport", content: "width=device-width, initial-scale=1" },
      {
        hid: "description",
        name: "description",
        content: process.env.npm_package_description || ""
      }
    ],
    link: [{ rel: "icon", type: "image/x-icon", href: "/favicon.ico" }]
  },
  /*
   ** Customize the progress-bar color
   */
  loading: { color: "#fff" },
  /*
   ** Global CSS
   */
  css: [],
  /*
   ** Plugins to load before mounting the App
   */
  plugins: [
    "~/plugins/global.js",
    { src: "~/plugins/vue2editor.js", ssr: false },
    { src: "~/plugins/datepicker.js", ssr: false }
  ],
  /*
   ** Nuxt.js dev-modules
   */
  buildModules: [
    // Doc: https://github.com/nuxt-community/nuxt-tailwindcss
    "@nuxtjs/tailwindcss"
  ],
  /*
   ** Nuxt.js modules
   */
  modules: [
    [
      "@nuxtjs/pwa",
      {
        workbox: {
          importScripts: [
            // ...
            "/firebase-auth-sw.js"
          ],
          // by default the workbox module will not install the service worker in dev environment to avoid conflicts with HMR
          // only set this true for testing and remember to always clear your browser cache in development
          dev: true
        }
      }
    ],
    [
      "nuxt-fontawesome",
      {
        component: "fa",
        imports: [
          {
            set: "@fortawesome/free-solid-svg-icons",
            icons: ["fas"]
          },
          {
            set: "@fortawesome/free-regular-svg-icons",
            icons: ["far"]
          }
        ]
      }
    ],
    [
      "@nuxtjs/firebase",
      {
        config: {
          apiKey: "AIzaSyCq0N5ieE9AzohIxihSKfWW38fn5bs8q6g",
          authDomain: "pro-cv-dev.firebaseapp.com",
          databaseURL: "https://pro-cv-dev.firebaseio.com",
          projectId: "pro-cv-dev",
          storageBucket: "pro-cv-dev.appspot.com",
          messagingSenderId: "981564830148",
          appId: "1:981564830148:web:b7f43fab9358e07fc2f491"
        },
        services: {
          auth: {
            ssr: true,
            initialize: {
              onAuthStateChangedAction: "auth/onAuthStateChanged"
            }
          },
          firestore: true
        }
      }
    ]
  ],
  /*
   ** Build configuration
   */
  build: {
    /*
     ** You can extend webpack config here
     */
    extend(config, ctx) {}
  }
};

And in store/index.js

export const actions = {
  async nuxtServerInit({ dispatch, commit }, { res }) {
    console.log("nuxt server init", res.locals);
    if (res && res.locals && res.locals.user) {
      console.log("res local user", res.locals.user);
      const { allClaims: claims, ...authUser } = res.locals.user;

      await dispatch("auth/onAuthStateChanged", { authUser, claims });
    }
  }
};

The only log I get is “nuxt server init {}” every time, even though I’m logged in and the client can log in fine, which creates a client/server render mismatch.

I’ve tried removing node_modules and yarn.lock and reinstalling, no luck. I’ve updated to 5.0.7 from 5.0.6 and @nuxtjs/pwa from 3.0.0 to 3.0.0-beta.20, no luck either.

I’ve deployed to firebase functions and it’s the same behavior.

I can see the service worker in Chrome Dev Tools Application tab, here is the source

importScripts('https://cdn.jsdelivr.net/npm/workbox-cdn@4.3.1/workbox/workbox-sw.js', '/firebase-auth-sw.js')

// --------------------------------------------------
// Configure
// --------------------------------------------------

// Set workbox config
workbox.setConfig({
  "debug": true
})

// Start controlling any existing clients as soon as it activates
workbox.core.clientsClaim()

// Skip over the SW waiting lifecycle stage
workbox.core.skipWaiting()

workbox.precaching.cleanupOutdatedCaches()

// --------------------------------------------------
// Precaches
// --------------------------------------------------

// Precache assets

// --------------------------------------------------
// Runtime Caching
// --------------------------------------------------

// Register route handlers for runtimeCaching
workbox.routing.registerRoute(new RegExp('/_nuxt/'), new workbox.strategies.NetworkFirst ({}), 'GET')
workbox.routing.registerRoute(new RegExp('/'), new workbox.strategies.NetworkFirst ({}), 'GET')

And I have this in .nuxt/index.js plugins

/* Plugins */

import nuxt_plugin_workbox_18867e94 from 'nuxt_plugin_workbox_18867e94' // Source: ./workbox.js (mode: 'client')
import nuxt_plugin_nuxticons_5ea60124 from 'nuxt_plugin_nuxticons_5ea60124' // Source: ./nuxt-icons.js (mode: 'all')
import nuxt_plugin_ssrAuth_0a0e039a from 'nuxt_plugin_ssrAuth_0a0e039a' // Source: ./firebase-module/ssrAuth.js (mode: 'server')
import nuxt_plugin_main_1f947c08 from 'nuxt_plugin_main_1f947c08' // Source: ./firebase-module/main.js (mode: 'all')
import nuxt_plugin_initAuth_e61ff4ee from 'nuxt_plugin_initAuth_e61ff4ee' // Source: ./firebase-module/initAuth.js (mode: 'client')
import nuxt_plugin_templatesplugin09ff87e9_17dec52e from 'nuxt_plugin_templatesplugin09ff87e9_17dec52e' // Source: ./templates.plugin.09ff87e9.js (mode: 'all')
import nuxt_plugin_global_f21f4e84 from 'nuxt_plugin_global_f21f4e84' // Source: ../plugins/global.js (mode: 'all')
import nuxt_plugin_vue2editor_65d66bc8 from 'nuxt_plugin_vue2editor_65d66bc8' // Source: ../plugins/vue2editor.js (mode: 'client')
import nuxt_plugin_datepicker_f86071f6 from 'nuxt_plugin_datepicker_f86071f6' // Source: ../plugins/datepicker.js (mode: 'client')

And this in .nuxt/firebase-module/ssrAuth.js

import admin from 'firebase-admin'

const options = {"credential":false,"config":{"apiKey":"AIzaSyCq0N5ieE9AzohIxihSKfWW38fn5bs8q6g","authDomain":"pro-cv-dev.firebaseapp.com","databaseURL":"https:\u002F\u002Fpro-cv-dev.firebaseio.com","projectId":"pro-cv-dev","storageBucket":"pro-cv-dev.appspot.com","messagingSenderId":"981564830148","appId":"1:981564830148:web:b7f43fab9358e07fc2f491"}}

const simulateUserRecord = ({
  uid,
  email,
  email_verified: emailVerified,
  name: displayName
}) => ({
  uid,
  email,
  emailVerified,
  displayName
})

if (!admin.apps.length) {
  if (options.credential) {
    const credential =
      typeof options.credential === 'boolean'
        ? admin.credential.applicationDefault()
        : admin.credential.cert(options.credential)

    admin.initializeApp({
      credential,
      ...options.config
    })
  } else {
    admin.initializeApp(options.config)
  }
}

export default async ({ req, res }) => {
  if (!req.headers.authorization) {
    return
  }

  // Parse the injected ID token from the request header.
  const authorizationHeader = req.headers.authorization || ''
  const components = authorizationHeader.split(' ')
  const idToken = components.length > 1 ? components[1] : ''

  try {
    // Try to verify the id token, additionally checking if the token was revoked
    const decodedToken = await admin.auth().verifyIdToken(idToken)

    if (decodedToken.uid) {
      const authUser = options.credential
        ? await admin.auth().getUser(decodedToken.uid)
        : simulateUserRecord(decodedToken)

      res.locals = {
        ...res.locals,
        user: {
          ...authUser,
          allClaims: decodedToken
        }
      }
    }
  } catch (e) {
    console.error(e)
  }
}

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:14 (4 by maintainers)

github_iconTop GitHub Comments

1reaction
Tardigrada777commented, Jun 4, 2020

Hey, i have no Authorization header, that ssrAuth.js expects, but i have my token in the cookie header of the req. image

0reactions
danlordycommented, Dec 26, 2021

Esto no funciona, no deberían cerrar la conversación

Read more comments on GitHub >

github_iconTop Results From Across the Web

node.js - res.locals is undefined? - Stack Overflow
I am trying to make an authetication middle to check if token received is valid and pass on the user data with ...
Read more >
azu on Twitter: "見てる: "[SSR Auth] res.locals is always an empty ...
見てる: "[SSR Auth] res.locals is always an empty object / res.locals.user always undefined · Issue #170 · nuxt-community/firebase-module". Translate Tweet.
Read more >
Res.locals.user - how does it work? - The freeCodeCamp Forum
Hey, still trying to figure out how to do the user authentication on my app. I have an example from a tutorial that...
Read more >
Client API - NextAuth.js
The NextAuth.js client library makes it easy to interact with sessions from React applications.
Read more >
Creating Server-side Rendered Vue.js Apps Using Nuxt.js
JavaScript frameworks/libraries such as Vue can offer a fantastic user ... You can always create a static site instead while still taking advantage...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found