#Missing cookies in request from server

26 messages · Page 1 of 1 (latest)

dusk obsidian
#

Hey I am trying to make ofetch call from the middleware to preload data into the store. Problem is that the call should include also cookies with auth information but as i am trying to console.log headers of this request made on server, there are no headers at all

#

When I was trying to do same on the client it was working but I want to utilize SSR

vivid mural
#

Show some codes

dusk obsidian
vivid mural
#

on ssr context and server middleware you could write header back to a request(event) using setHeader
import { setHeader } from "h3";
setHeader(useRequestEvent()!, "set-cookie", cookies);

dusk obsidian
#

Hm interesting I will try and let you know 🙂

vivid mural
#

use useRequestHeaders to get access to request cookies

#

there is also setResponseHeaders


export default defineEventHandler((event) => {
  setResponseHeaders(event, {
    "content-type": "text/html",
    "cache-control": "no-cache",
  });
});


dusk obsidian
#

I am getting this error:

#

I am unable to use this function in server context

vivid mural
vivid mural
dusk obsidian
vivid mural
#

your request is in event object you should be able to see it if you log

dusk obsidian
#

Look so this is the issue i am trying to explain, when I am sending initial request to page cookies exist (you can see the first one), but then server tries to fetch data from other API and cookies are missing

  logger.log("Where:", event.path);
  const cookieRaw = getCookie(event, "auth.access-token");
  const cookie = cookieRaw ? (JSON.parse(cookieRaw) as JwtToken) : null;
  if (cookie) {
    setCookie(event, "auth.access-token", JSON.stringify(cookie));
  }
  logger.log("Original cookie", cookie);
#

Data fetching runs in middleware

vivid mural
dusk obsidian
vivid mural
#

I fixed the issue by using middleware combined with a timestamp to track the JWT token's expiry date. In my case, the token was set to expire after 20 minutes. In the middleware, I check if the token has expired, and if so, I handle the refresh, pass the updated cookies, and continue with the request. also have a custom useAuth composable with a useState inside to keep track of cookie expiry on the client side. Additionally, I use a Redis instance on the backend to cache both the JWT and the refresh token for one minute. This ensures that if any subsequent requests fail to get the cookie from the frontend, I can return it directly from the cache. instead of generating new one ( in my case i revoke previous refresh tokens )
simplfied version


import { setHeader } from "h3";
import { useAuth } from "~/composable/useAuth";

export default defineNuxtRouteMiddleware(async () => {
    const { isRefreshNeeded, refreshCSR, refreshSSR, setCookieCSR } = useAuth();

    if (import.meta.server) {
        if (isRefreshNeeded()) {
            try {
                const { cookies, exp } = await refreshSSR(useRequestHeaders());

                cookies.push(`exp=${exp}; Path=/`);
                setHeader(useRequestEvent()!, "set-cookie", cookies);

                return true;
            }
            catch {
                return navigateTo("/auth/login");
            }
        }
    }

    if (import.meta.client) {
        if (isRefreshNeeded()) {
            try {
                await refreshCSR(useRequestHeaders());
                setCookieCSR();
                return true;
            }
            catch {
                return navigateTo("/auth/login");
            }
        }
    }
});

dusk obsidian
#

But as I am trying to explain, my cookies are lost in communication between nuxt server and external server.

dusk obsidian
vivid mural