[SSR Auth] res.locals is always an empty object / res.locals.user always undefined
See original GitHub issueI’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:
- Created 3 years ago
- Comments:14 (4 by maintainers)
Hey, i have no
Authorization
header, thatssrAuth.js
expects, but i have my token in thecookie
header of thereq
.Esto no funciona, no deberían cerrar la conversación