Next.js Discord

Discord Forum

Cookie not available on first "set()"

Unanswered
Clown posted this in #help-forum
Open in Discord
I have a child layout that uses a organization cookie and the cookie is set from the following middleware code:
import {
  withMiddlewareAuthRequired,
} from "@auth0/nextjs-auth0/edge";
import { NextResponse } from "next/server";
import { API_ORGANIZATION_PATH, BASE_URL, DASHBOARD_BASE_PATH } from "./app/api/api_constants";

export default withMiddlewareAuthRequired(async function middleware(req) {

  const newHeaders = new Headers(req.headers);
  newHeaders.set("Authorization", `BEARER ${process.env.INTERNAL_SECRET}`);
  const organization = await fetch(API_ORGANIZATION_PATH, {
    headers: newHeaders,
  });

  if (organization.ok) {
    const response = NextResponse.next();
    response.cookies.set("organization", JSON.stringify((await organization.json())));

    if (req.nextUrl.pathname.endsWith("/dashboard/organization/create")) {
      return NextResponse.redirect(DASHBOARD_BASE_PATH);
    }

    return response;
  }
  else {
    switch (organization.status) {
      case 401:
        return NextResponse.json({ error: "Unauthorized", }, { status: 401 });
      case 404:
        if (!req.nextUrl.pathname.endsWith("/dashboard/organization/create")) {
          return NextResponse.redirect(
            `${BASE_URL}/dashboard/organization/create/`,
          );
        }
        break;
    }
  }

});

export const config = { matcher: ["/dashboard/:path*"] };


Problem is, if the cookie does not exist already this ends up causing a application error in my code. I want to know why the cookie is not available on the very first time the cookie gets created. I am probably going to look into alternative ways soon but i want to know what i am missing.

11 Replies

Uh... Bump
you need to give us shorter code. your code is 41 lines, that's too long. make a simple reproduction example.
@joulev you need to give us shorter code. your code is 41 lines, that's too long. make a simple reproduction example.
Alright I'll shorten it up soon or try to create minimum reproduction example
Toyger
cookies are not set until they reach client.
you probably trying to access them until response with Set-Cookie was received by clilent.
only next request will have new cookies that was set in previous.
@Toyger cookies are not set until they reach client. you probably trying to access them until response with `Set-Cookie` was received by clilent. only next request will have new cookies that was set in previous.
Its being used in the layout.

If what you're saying is correct (and it makes sense now that i think about it), then i get what could be happening.

I thought, just sending the cookie through nextReponse would be good enough for it to be picked by the layout (which would be run AFTER middleware ofc).
This could also be why it gives me an error the first time but not afterwards (since its using the cookie from the previous response)
But then what would be a good way around it? Im already doing a fetch now in my app as an alternative after cleaning up some of the mess, so while its not a immediate issue, its still good to know what could be done.
Toyger
one of ways is use headers, which will change immidiately for next request, but, I am not sure about layout, it have some strange cache strategy so it possible that it will just not be called at the moment when you change page. what are you trying to achieve? probably it should be done differently.
@Toyger one of ways is use headers, which will change immidiately for next request, but, I am not sure about layout, it have some strange cache strategy so it possible that it will just not be called at the moment when you change page. what are you trying to achieve? probably it should be done differently.
Im sending some information about a "organization" through the cookies. When i wrote the code there was the authorization header being used which i didnt want to spam all around my code. Its now removed so i have simply removed the entire cookie and now im directly doing a fetch for the organization.

As for why it is being done in the middleware is simply because i wanted the data to be up-to-date.
@Clown Im sending some information about a "organization" through the cookies. When i wrote the code there was the authorization header being used which i didnt want to spam all around my code. Its now removed so i have simply removed the entire cookie and now im directly doing a fetch for the organization. As for why it is being done in the middleware is simply because i wanted the data to be up-to-date.
Toyger
you can put data into some header and work with it, a bit redundant but possibly will work, but also as I said layout itself have strange behaviour, so you need to test it.
and if you need to be so up to date, then it's probably easier to use websockets.
@Toyger you can put data into some header and work with it, a bit redundant but possibly will work, but also as I said layout itself have strange behaviour, so you need to test it. and if you need to be so up to date, then it's probably easier to use websockets.
Hmm, i guess I'll separately test cookies with layout.

Its not needed in the app anymore and i dont need to instantly react to changes either since just updating on page change is good enough.