[Vuejs]-Nuxt useFetch not getting cookies when page reload

0👍

First of all, ensure that your server sets Access-Control-Allow-Credentials to be true:

res.header('Access-Control-Allow-Credentials', 'true');

Also, add this config to your useFetch:

const { data: posts } = await useFetch(url, {
  credentials: 'include',
});

And remember on the server, during SSR, cookies from the incoming request might not be attached to fetch automatically. To ensure cookies are forwarded to the fetch request during SSR, you might need to pass them explicitly.

Since it’s not directly straightforward with useFetch, consider using serverMiddleware to check and forward the cookie during SSR.

if (process.server) {
  const cookie = req.headers.cookie;
}

And lastly, ensure the HttpOnly cookie is set with the right domain and path. If your API and Nuxt app are on different subdomains, set the cookie’s domain accordingly to ensure it’s accessible.

Hope this helps!


EDIT

Let’s add some details how to use my previous answer.

So, Create a middleware ( for example middleware/cookieForwarder.js):

export default function (context) {
  if (process.server) {
    context.ssrContext.req.serverCookie = context.req.headers.cookie;
  }
}

Then, use it in component:

<script setup>
    definePageMeta({
        middleware: ['auth', 'cookieForwarder']
    })

    let serverCookie;

    if (process.server) {
        serverCookie = useContext().ssrContext.req.serverCookie;
    }

    const headers = {};

    if (serverCookie) {
        headers['Cookie'] = serverCookie;
    }

    const {data: posts} = await useFetch(useRuntimeConfig().public.API_URL + '/api/posts', {
        credentials: 'include',
        headers: headers
    });
</script>

In your express app (appropriate header and CORS realted settings):

const express = require('express');
const cors = require('cors');

const app = express();

app.use(cors({
    origin: 'YOUR_NUXT_APP_URL_HERE', // e.g., 'http://localhost:3000'
    credentials: true
}));

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Credentials', 'true');
    next();
});

And in your route in express app:

res.cookie('cookieName', 'cookieValue', {
    httpOnly: true,
    domain: 'YOUR_DOMAIN_HERE',  // e.g., '.yourdomain.com' (the leading dot is for subdomains)
    path: '/'
});

Consider that the last part is somehow abstract since you didn’t provided much details for express server. But this will do the job.

Hope this helps again!

Leave a comment