NuxtJs执行npm run generate报错:Cannot read property 'headers' of undefined
npm run generate Hey there! Congrats on your first project at the new company—let's get this Nuxt.js issue sorted out quickly.
The root of your problem is straightforward: when you run npm run generate, Nuxt operates in static site generation mode—it doesn’t spin up a server, so there’s no incoming request (req) object available in nuxtServerInit. That’s why accessing req.headers.cookie throws the "Cannot read property 'headers' of undefined" error.
Here’s how to fix it step by step:
1. Guard req access in nuxtServerInit
First, update your store/index.js to check if req exists before trying to parse cookies. This skips the server-side cookie logic entirely during static generation:
import Vuex from 'vuex' var cookieparser = require('cookieparser') const createStore = () => { return new Vuex.Store({ state: { auth: null, }, mutations: { update (state, data) { state.auth = data } }, actions: { nuxtServerInit ({ commit }, { req }) { // Exit early if req doesn't exist (static generation mode) if (!req) { commit('update', null) return } let accessToken = null if (req.headers.cookie) { const parsed = cookieparser.parse(req.headers.cookie) if (parsed) { accessToken = parsed.auth } } commit('update', accessToken) }, } }) } export default createStore
2. Restore auth state on the client side
Static generated pages don’t have server-side context, so when a logged-in user loads your static site, the store won’t automatically pick up the auth cookie. Add logic to your middleware to sync the cookie with the store on the client:
Update middleware/authenticated.js:
export default function ({ store, redirect }) { // If we're on the client, pull auth from cookie and update the store if (process.client) { const authCookie = document.cookie.split('; ').find(row => row.startsWith('auth=')) if (authCookie) { // Decode the cookie value (since you stored an object) const auth = JSON.parse(decodeURIComponent(authCookie.split('=')[1])) store.commit('update', auth) } } // Redirect to login if still not authenticated if (!store.state.auth) { return redirect('/login') } }
And update middleware/notAuthenticated.js similarly (to avoid incorrect redirects for logged-in users):
export default function ({ store, redirect }) { if (process.client) { const authCookie = document.cookie.split('; ').find(row => row.startsWith('auth=')) if (authCookie) { const auth = JSON.parse(decodeURIComponent(authCookie.split('=')[1])) store.commit('update', auth) } } if (store.state.auth) { return redirect('/app/dashboard') } }
Why this works
- During
npm run generate,nuxtServerInitskips cookie parsing becausereqis undefined, preventing the error. - When a user loads the static site in their browser, the middleware runs on the client, reads the auth cookie from the browser, and updates the store—so your authentication checks work as expected.
Quick note on static generation vs SSR
Keep in mind that static generation is ideal for content that doesn’t change often, but if your project relies heavily on server-side auth or dynamic data, you might want to consider Nuxt’s SSR mode (npm run build + npm run start) instead. But if static generation is a requirement, the above fixes should get you up and running.
内容的提问来源于stack exchange,提问作者Fury06

