You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Nuxt.js SSR场景下无法获取浏览器Cookie的解决方案咨询

Great question—this is a common gotcha with Nuxt SSR since server-side code can’t access browser cookies directly. Let’s walk through the solution step by step:

Solution Overview

The core idea is to:

  1. Pass the browser’s cookie (containing your API result) to the server during SSR initialization.
  2. Configure Axios to automatically inject this value into request headers for both server-side and client-side requests.

Nuxt provides the nuxtServerInit action in your Vuex store, which runs on the server every time a user loads your app. Here, you can access the incoming request’s headers (including cookies) and store the needed value in Vuex for later use.

In store/index.js:

export const state = () => ({
  apiToken: '' // The value you need to add to Axios headers
})

export const mutations = {
  SET_API_TOKEN(state, token) {
    state.apiToken = token
  }
}

export const actions = {
  async nuxtServerInit({ commit }, context) {
    // Get the raw cookie string from the request headers
    const cookieHeader = context.req.headers.cookie || ''
    
    // Extract your specific token from the cookie (adjust the key to match yours)
    const tokenCookie = cookieHeader.split(';').find(c => c.trim().startsWith('api_token='))
    const apiToken = tokenCookie ? tokenCookie.split('=')[1] : ''
    
    // Store the token in Vuex so Axios can access it later
    commit('SET_API_TOKEN', apiToken)
  }
}

Step 2: Configure Axios Interceptors

Next, create an Axios plugin to set up request interceptors that add your token to headers, whether the request is running on the server or client.

In plugins/axios.js (make sure to register this plugin in nuxt.config.js under plugins):

export default function ({ $axios, store, req }) {
  // Intercept every outgoing Axios request
  $axios.interceptors.request.use(config => {
    let apiToken
    
    // For server-side requests: pull the token from Vuex
    if (process.server) {
      apiToken = store.state.apiToken
    } 
    // For client-side requests: extract directly from browser cookies
    else {
      const tokenCookie = document.cookie.split(';').find(c => c.trim().startsWith('api_token='))
      apiToken = tokenCookie ? tokenCookie.split('=')[1] : ''
    }

    // Add the token to your request header (adjust the header name to match your backend's requirements)
    if (apiToken) {
      config.headers['X-API-Token'] = apiToken
    }

    return config
  })
}

Don’t forget to register the plugin in nuxt.config.js:

export default {
  plugins: ['~/plugins/axios.js']
}

If the user is visiting your app for the first time (and doesn’t have the cookie yet), you’ll need to fetch the value from your API first, store it in a cookie, and then use it for subsequent requests. You can handle this directly in nuxtServerInit:

async nuxtServerInit({ commit }, { $axios, req, res }) {
  let apiToken = ''
  const cookieHeader = req.headers.cookie || ''
  const tokenCookie = cookieHeader.split(';').find(c => c.trim().startsWith('api_token='))

  if (tokenCookie) {
    apiToken = tokenCookie.split('=')[1]
  } else {
    // Fetch the token from your backend API
    const response = await $axios.$get('/api/your-token-endpoint')
    apiToken = response.token

    // Set the cookie on the client (server-side uses res.setHeader)
    res.setHeader('Set-Cookie', `api_token=${apiToken}; Path=/; HttpOnly; SameSite=Strict`)
  }

  commit('SET_API_TOKEN', apiToken)
}

Key Notes to Keep in Mind

  • HttpOnly Cookies: If your cookie is marked as HttpOnly, client-side JavaScript can’t access it—this is good for security! In this case, rely entirely on the server-side logic (pull from req.headers.cookie in nuxtServerInit and use the Vuex value in Axios interceptors).
  • Cookie Parsing: For more complex cookie parsing, consider using a lightweight library like cookie (install via npm i cookie) instead of splitting strings manually. Example with cookie:
    import cookie from 'cookie'
    
    const parsedCookies = cookie.parse(req.headers.cookie || '')
    const apiToken = parsedCookies.api_token || ''
    
  • Axios Instance Isolation: Nuxt creates a fresh Axios instance for each server-side request, so you don’t have to worry about cross-request contamination.

内容的提问来源于stack exchange,提问作者soarinblue

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:26:08