Next.js Discord

Discord Forum

Set cookie from page

Answered
Velvet ant posted this in #help-forum
Open in Discord
Velvet antOP
Hi!

I have a page where there is route params and search params.
What would be the best way to set a cookie with data coming from the search param ?
Since we can only set cookie in a action or in a route handler I dont know what is the best way ?

Actually I have a to create a client component that fetch a route handler in a useEffect to set cookies. It works but I feel that there is a other way to do it.

// 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;
}


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

  return <SetSession /> // here I pass params and search prams as props
}
Answered by Velvet ant
I find a solution, I can register the session on click with a server action.
View full answer

1 Reply

Velvet antOP
I find a solution, I can register the session on click with a server action.
Answer