Next.js Discord

Discord Forum

Set cookie depending on search params

Answered
Velvet ant posted this in #help-forum
Open in Discord
Velvet antOP
I have a route where there is some search params. How can I set a cookie directly ? Should I go with a route handler ? or maybe a middleware ?
Answered by riský
ah ok, its because middleware has its api slightly diferent: https://nextjs.org/docs/app/building-your-application/routing/middleware#using-cookies

export function middleware(request: NextRequest) {
  // Setting cookies on the response using the `ResponseCookies` API
  const response = NextResponse.next()
  response.cookies.set({
    name: 'vercel',
    value: 'fast',
    path: '/',
  })
 
  return response
}
View full answer

21 Replies

well, can you explain your usecase more so we can give better answer (like hard to know whats best out of those options without knowing)
Velvet antOP
sure.

I have a route like /register/personal?token=xxx&email=xxxx&test=xxxx
I also have a cookie session where I want to store those search params.
I need the token from search params to perform a fetch and get others datas that will be set inside the cookie session.
Actually, I set the cookie when the user click on a button, it uses a server action to set cookies.
But the thing is I need data from cookie in the upper layout before user click.

And since we can only set cookie in actions or route handlers, the middleware option wont work.
I also tried with a route handlers but it seems that I need to have a client component to fetch the route handler inside a useEffect.

// client component
"use client";

import { useEffect } from "react";
import { env } from "@/env.mjs";
import type { RegisterParams, RegisterScope } from "@/lib/viktor/user/register";

type Props = {
  scope: RegisterScope;
  params: RegisterParams;
};

export function SetSession(props: Props) {
  useEffect(() => {
    fetch(`${env.NEXT_PUBLIC_APP_URL}/api/register/cookie`, {
      method: "POST",
      body: JSON.stringify(props),
    });
  }, [props]);

  return null;
}

// Page
export default async function Page({
  params,
  searchParams,
}: {
  params: Params;
  searchParams: SearchParams;
}) {

  return <SetSession /> // here I pass params and search prams as props
}
Actually it was already a question that I asked. I thought that I found a solution but since I need the cookie without user action, my solution was wrong
To add detail on this. I need the cookie to set the branding ( colour, image) of a page. So I guess if I set the cookie with a route handler client side, at first user will see a page without branding and then the branding will be there. I want to avoid that if possible
Velvet antOP
One more thing:
I tries to directly call the route handler in the page but it seems to not set the cookie in the browser.

So yeah I think I'm missing something
@riský I hope this is clear, if not I can maybe add other detail 🙂
And since we can only set cookie in actions or route handlers, the middleware option wont work.
you can set in middleware tho (its just page and layout get streamed to client, and thus cant add headers)
Velvet antOP
I tried, next gives me an error, so maybe because I use cookie from next/headers ?
I can read the cookie but I cant set it
ah ok, its because middleware has its api slightly diferent: https://nextjs.org/docs/app/building-your-application/routing/middleware#using-cookies

export function middleware(request: NextRequest) {
  // Setting cookies on the response using the `ResponseCookies` API
  const response = NextResponse.next()
  response.cookies.set({
    name: 'vercel',
    value: 'fast',
    path: '/',
  })
 
  return response
}
Answer
also note, you may want to modify the request cookies before .next too (so your page can actually use - idk what your use case and if it is doing ssr fetching)
Velvet antOP
so I guess I need to use a different cookie than my cookie session ?
additionally, if your cookie isnt httpOnly and your route handler is just setting, you can directly modify on client
document.cookie = `thing=${thingg}; path=/; Expires=Fri, 31 Dec 9999 23:59:59 GMT;`
but regarding your styling, this would just set cookie, and you would still need to make the compnents and things use the new styling
Velvet antOP
What I want is:
- get search params
- fetch some data with token coming from search params
- store data in a cookie ( some colors for example )
- render the page with the color from cookie

so I think with your solution, I will set a specific cookie for the styling part. it should be good I guess.
I would use local storage for something like that imo.
Similarly to how shadcn implements their dark/light mode
yeah that can be better idea (as it can still be done in a way withoutfouc flash of unstyled content)
Velvet antOP
hmm ok let me try that
if its just themes, have a look at next-themes as it does alot for you!
Velvet antOP
ok thx and I have also shadcn in the project