Next.js Discord

Discord Forum

Getting client side set cookies values in _middleware.js

Unanswered
Kuchi posted this in #help-forum
Open in Discord
KuchiOP
getting undefined even though the cookie gets set client side

client side setting of cookie + setting it in server so middleware can read it
import Cookies from "js-cookie";
export default function () {
  const [province, setProvince] = useState(null);
  const getCookie = (name) => {
    return Cookies.get(name);
  };
  useEffect(() => {
    // Function to get the "PROVINCE" cookie and set it in the component state
    const getCookie = (name) => {
      return Cookies.get(name);
    };

    const provinceCookie = getCookie("PROVINCE");
    setProvince(provinceCookie);
  }, []);

  const setCookie = (locale) => {
    // Function to set the "PROVINCE" cookie
    document.cookie = `PROVINCE=${locale}; max-age=31536000; path=/`;
  };

  const handleChangeProvince = (locale) => {
    // Function to handle the province change and make an API request
    setCookie(locale);

    fetch("/api/setProvince", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ locale }),
    })
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
      })
      .catch((error) => {
        console.error("Error:", error);
        // Handle errors if any
      });

    router.push(router.asPath, undefined);
  };

/api/setProvince
// pages/api/setProvince.js

export default function handler(req, res) {
    const { locale } = req.body;
  
    // Set the "PROVINCE" cookie in the response
    res.setHeader(
      "Set-Cookie",
      `PROVINCE=${locale}; Max-Age=31536000; Path=/`
    );
  
    // Respond with a success message or any other data if needed
    res.status(200).json({ message: "Province cookie set successfully" });
  }


import { NextResponse } from "next/server";

import { parse } from 'cookie';


export const middleware = async (req) => {
  const cookies = parse(req.headers.cookie || '');

  const provinceCookie = cookies['PROVINCE'];
  console.log("Province", provinceCookie) //shows as undefined

4 Replies

Tramp ant
request received by middleware is of type NextRequest. You can find the cookies in req.cookies
@Tramp ant Click to see attachment
KuchiOP
works, thanks koan