Skip to content

getCookie return undefined only on ssr #21282

@mrc-bsllt

Description

@mrc-bsllt

Environment

  • Operating System: Darwin
  • Node Version: v16.18.1
  • Nuxt Version: 3.5.1
  • Nitro Version: 2.4.1
  • Package Manager: yarn@1.22.19
  • Builder: vite
  • User Config: runtimeConfig, devServer, vite, typescript, css, modules, tailwindcss
  • Runtime Modules: @nuxtjs/tailwindcss@6.7.0, @pinia/nuxt@0.4.11, @nuxt/image-edge@1.0.0-28059208.2abef1b
  • Build Modules: -

Reproduction

https://stackblitz.com/edit/nuxt-starter-ugzbfq

Describe the bug

I premise that I don't know if it makes more sense to put this issue here, or on h3. I am trying to read a cookie in a nuxt server api. As written in the documentation, I am using the getCookie() fuction to which I pass event and the name of the cookie, but when I resfresh the page it always returns undefined. On the client side, everything works correctly.
This is the code of my server api:

import validator from "validator"

export default defineEventHandler(event => {
  const authorization = getHeader(event, "Authorization")
  const token = authorization?.split(" ")[1] || ""
  const isValid = validator.isUUID(token)
  const validToken = getCookie(event, "validToken")
  const validTokenExistAndIsNotEqualToToken = validToken && validToken !== token

  console.log("validToken", validToken) // undefined on server side

  if (!token || !isValid || validTokenExistAndIsNotEqualToToken) {
    throw createError({
      statusCode: 401,
      statusMessage: "Unauthorized"
    })
  }

  if (!validToken) {
    throw createError({
      statusCode: 403,
      statusMessage: "Forbidden"
    })
  }

  return {
    stringMessage: "This is a secret message from the server"
  }
})

Screenshot 2023-05-31 alle 11 52 37

Additional context

No response

Logs

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions