简体   繁体   中英

How to access httpOnly cookies from Nuxt 3 server

I am implementing a login feature to a website project. The backend is Express and the frontend is Nuxt 3. Upon successfully authenticating a user login, the Express backend returns necessary data to the webserver, which then creates an httpOnly cookie and sets any necessary data in a Pinia store. On page refresh, I would like the Nuxt 3 server to look at the cookie and setup the Pinia store (since it is lost on page refresh).

Can someone provide some guidance? I have looked at the useNuxtApp() composable, and I can see the cookie in nuxtApp.ssrContext.req.headers.cookie , but that only provides a K/V pairing of all set cookies, which I would need to parse. I know of the useCookie composable, but that only works during Lifecycle hooks, which seems to only resolve undefined .

Thanks.

Not sure if this is the right way, but it's a solution I used to get through a similar case - do.net api + nuxt3 client.

First, we need to proxy API (express in your case), this will make it, so our cookie is on the same domain and browser will start sending it to /api/ endpoints.

  1. Install @nuxtjs-alt/proxy - npm i @nuxtjs-alt/proxy .
  2. Add configuration to nuxt.config.ts (my api running on localhost:3000):

nuxt.config.ts :

export default defineNuxtConfig({
  modules: [
    '@nuxtjs-alt/proxy'
  ],
  proxy: {
    enableProxy: true,
    fetch: true,
    proxies: {
      '/proxy': {
        target: 'http://localhost:3000',
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/proxy/, '')
      }
    }
  }
});

Then we can the request that will set a cookie anywhere on client using proxy instead of a direct call.

Anywhere on client, do a request using newly setup proxy instead of calling API directly.

Adjust parameters based on your setup.

await $fetch('/proxy/user/sign-in', {
  method: 'POST',
  body: {
    email: 'example@mail.com',
    password: 'password'
  }
});

Ultimately, should end up with a cookie set on our client domain.

And lastly, when we handle request client side - we read the cookie and set up on forwarding request. Replace COOKIE_NAME and API URL accordingly.

server/api/user/me.get.ts :

export default defineEventHandler(async (event) => {
  return await $fetch('http://localhost:3000/user/me', {
    headers: {
      Cookie: `COOKIE_NAME=${
        getCookie(event, 'COOKIE_NAME')
      }`
    }
  });
});

API call will use the same cookie we got when we did a first request using cookie and the server should be able to read it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM