Setting cookie in a Nuxt 3 (npm run dev) server from a Golang Echo API
Asked Answered
S

1

6

I have a Nuxt 3 (^3.0.0-rc.11) frontend and a Golang Echo v4 backend API.

The ssr property is set to false in the nuxt.config.ts file, so when I run npm run generate, I can serve the static generated files from the echo API, and the session cookie I am sending from the backend is getting set in the browser as expected.

BUT, when i run npm run dev from nuxt, the cookie is not set in the browser, even if I can see it in the response headers (under network tab in Firefox).

I may believe it does not work for the dev server because nuxt is running on port :3000 and echo on :1323, and there may be CORS issues?

I have tried to follow the tips from Set cookies for cross origin requests but to no avail. I'm not sure if this even is the issue in my case.

I even have tried to create a nuxt composable from v3.nuxtjs.org, but again, I'm not sure if this is the issue.

server.go

e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
    AllowOrigins: []string{"http://localhost:3000"},
    AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept},
    AllowCredentials: true,
 }))

session.go

session, _ := store.Get(c.Request(), "session")
session.Options = &sessions.Options{
    Path:     "/",
    MaxAge:   86400 * 7, // 7 days
    HttpOnly: true,
    Secure:   true,
    SameSite: http.SameSiteNoneMode,
}
 session.Values["authenticated"] = true
 session.Values["user_id"] = user.ID
 session.Save(c.Request(), c.Response())

authStore.js (pinia)

const { data } = await useAsyncData('login', () => $fetch(API_URL + '/api/login', {
    method: 'post',
    body: params,
    withCredentials: true,
})

I can set cookies from the Nuxt frontend with useCookie(), but I don't know how to fetch the set-cookie that are already there in the network tab.

Sullivan answered 5/10, 2022 at 18:42 Comment(1)
As the answer for the issue you linked states in its sidenote at the very end, the reason your cookies aren't stored might be because Google Chrome doesn't set cookies when using localhost with a port. You might want to try to setup a custom domain for your local apps.Orthicon
F
1

You can use getCookie() from h3 when the cookie is set by the API (i.e. not by Nuxt).


export default defineEventHandler(event =>
  // Read counter cookie
  let counter = getCookie(event, 'counter') || 0
  // Increase counter cookie by 1
  setCookie(event, 'counter', ++counter)
  // Send JSON response
  return { counter }

https://nuxt.com/docs/api/composables/use-cookie/#handling-cookies-in-api-routes

Flak answered 18/11, 2022 at 5:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.