next.js - Next JS 14 Setting Cookie In Layout - Stack Overflow

Im trying to fetch and essentially cache the data using cookies, but I'm getting an error when cre

Im trying to fetch and essentially cache the data using cookies, but I'm getting an error when creating the cookies. I'm not sure if I'm allowed to fetch and store data in the layout file itself. Can someone help me better understand

student/Layout.tsx

import type { Metadata } from "next";
import "../globals.css";
import Sidebar from "@/app/components/templates/sidebar";
import {
  Home,
  Calendar,
  BookOpenText,
  LibraryBig,
  ClipboardList,
  Waypoints,
} from "lucide-react";

import { Montserrat } from "next/font/google";
import { fetchServerSession } from "../backend/lib/hooks/getServerSession";
import { fetchStudentData } from "../backend/lib/onLoad/student/fetchStudentData";
import fetchEvents from "../backend/lib/onLoad/all/fetchEvents";
import { createCookie } from "../backend/lib/cookies/create";
import { redirect } from "next/navigation";

async function fetchAndCacheData() {
  "use server";
  const session = await fetchServerSession();

  if (!session?.user) {
    redirect("/");
  }

  const schoolId = session?.user?.school_id;
  const student_id = session?.user?.id;

  // Use Promise.all to fetch both promises concurrently
  const [studentData, events] = await Promise.all([
    fetchStudentData(schoolId?.toString() ?? "", student_id?.toString() ?? ""),
    fetchEvents(schoolId?.toString() ?? ""),
  ]);

  await Promise.all([
    createCookie("studentData", studentData),
    createCookie("events", events),
  ]);
}

await fetchAndCacheData();

const montserrat = Montserrat({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  const navigationItems = [
    {
      name: "Dashboard",
      href: "/student/dashboard",
      icon: <Home />,
      current: true,
    },

    {
      name: "Calendar",
      href: "/student/calendar",
      icon: <Calendar />,
      current: false,
    },
    {
      name: "Classes",
      href: `/student/classes`,
      icon: <BookOpenText />,
      current: false,
    },
    {
      name: "Study Material",
      href: "/student/studyMaterial",
      icon: <LibraryBig />,
      current: false,
    },
    {
      name: "Tests & Assingments",
      href: "/student/tests+assignments",
      icon: <ClipboardList />,
      current: false,
    },
    {
      name: "Learning Paths",
      href: "/student/learningPaths",
      icon: <Waypoints />,
      current: true,
    },
  ];

  return (
    <html lang="en h-full bg-gray-100">
      <body className={`${montserrat.className} antialiased bg-lightBg`}>
        <Sidebar navigation={navigationItems} />
        <main className="py-10 lg:pl-72">
          <div className="px-4 sm:px-6 lg:px-8">{children}</div>
        </main>
      </body>
    </html>
  );
}

lib/cookies/create.ts

"use server";
import { cookies } from "next/headers";
import { Encrypt } from "../encryption/encrypt";

export async function createCookie(name: string, data: any) {
  try {
    // Encrypt data
    const encryptedData = await Encrypt(data);

    // Set session cookie
    cookies().set({
      name: name,
      value: encryptedData,
      httpOnly: true,
      sameSite: "strict",
      secure: process.env.NODE_ENV === "production",
      path: "/",
    });

    return true;
  } catch (err) {
    console.error(`Error creating cookie: ${name}`, err);
    return false;
  }
}

Error creating cookie: studentData tA [Error]: Cookies can only be modified in a Server Action or Route Handler.

Im trying to fetch and essentially cache the data using cookies, but I'm getting an error when creating the cookies. I'm not sure if I'm allowed to fetch and store data in the layout file itself. Can someone help me better understand

student/Layout.tsx

import type { Metadata } from "next";
import "../globals.css";
import Sidebar from "@/app/components/templates/sidebar";
import {
  Home,
  Calendar,
  BookOpenText,
  LibraryBig,
  ClipboardList,
  Waypoints,
} from "lucide-react";

import { Montserrat } from "next/font/google";
import { fetchServerSession } from "../backend/lib/hooks/getServerSession";
import { fetchStudentData } from "../backend/lib/onLoad/student/fetchStudentData";
import fetchEvents from "../backend/lib/onLoad/all/fetchEvents";
import { createCookie } from "../backend/lib/cookies/create";
import { redirect } from "next/navigation";

async function fetchAndCacheData() {
  "use server";
  const session = await fetchServerSession();

  if (!session?.user) {
    redirect("/");
  }

  const schoolId = session?.user?.school_id;
  const student_id = session?.user?.id;

  // Use Promise.all to fetch both promises concurrently
  const [studentData, events] = await Promise.all([
    fetchStudentData(schoolId?.toString() ?? "", student_id?.toString() ?? ""),
    fetchEvents(schoolId?.toString() ?? ""),
  ]);

  await Promise.all([
    createCookie("studentData", studentData),
    createCookie("events", events),
  ]);
}

await fetchAndCacheData();

const montserrat = Montserrat({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  const navigationItems = [
    {
      name: "Dashboard",
      href: "/student/dashboard",
      icon: <Home />,
      current: true,
    },

    {
      name: "Calendar",
      href: "/student/calendar",
      icon: <Calendar />,
      current: false,
    },
    {
      name: "Classes",
      href: `/student/classes`,
      icon: <BookOpenText />,
      current: false,
    },
    {
      name: "Study Material",
      href: "/student/studyMaterial",
      icon: <LibraryBig />,
      current: false,
    },
    {
      name: "Tests & Assingments",
      href: "/student/tests+assignments",
      icon: <ClipboardList />,
      current: false,
    },
    {
      name: "Learning Paths",
      href: "/student/learningPaths",
      icon: <Waypoints />,
      current: true,
    },
  ];

  return (
    <html lang="en h-full bg-gray-100">
      <body className={`${montserrat.className} antialiased bg-lightBg`}>
        <Sidebar navigation={navigationItems} />
        <main className="py-10 lg:pl-72">
          <div className="px-4 sm:px-6 lg:px-8">{children}</div>
        </main>
      </body>
    </html>
  );
}

lib/cookies/create.ts

"use server";
import { cookies } from "next/headers";
import { Encrypt } from "../encryption/encrypt";

export async function createCookie(name: string, data: any) {
  try {
    // Encrypt data
    const encryptedData = await Encrypt(data);

    // Set session cookie
    cookies().set({
      name: name,
      value: encryptedData,
      httpOnly: true,
      sameSite: "strict",
      secure: process.env.NODE_ENV === "production",
      path: "/",
    });

    return true;
  } catch (err) {
    console.error(`Error creating cookie: ${name}`, err);
    return false;
  }
}

Error creating cookie: studentData tA [Error]: Cookies can only be modified in a Server Action or Route Handler.

Share Improve this question asked Nov 20, 2024 at 0:24 Guilherme AbreuGuilherme Abreu 32 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

The error occurs because you are trying to modify cookies directly in the layout component, which is not allowed. Cookie modification need to happen within a Server Action of Route Handler. Move the logic into a dedicated server action.

student/action.ts

import { fetchStudentData } from "../backend/lib/onLoad/student/fetchStudentData";
import fetchEvents from "../backend/lib/onLoad/all/fetchEvents";
import { createCookie } from "../backend/lib/cookies/create";

export async function initializeData(schoolId?: string, studentId?: string) {
  if (!schoolId || !studentId) {
    throw new Error("Missing required parameters");
  }

  try {
    // Use Promise.all to fetch both promises concurrently
    const [studentData, events] = await Promise.all([
      fetchStudentData(schoolId.toString(), studentId.toString()),
      fetchEvents(schoolId.toString()),
    ]);

    // Set cookies using Promise.all
    await Promise.all([
      createCookie("studentData", studentData),
      createCookie("events", events),
    ]);

    return { success: true };
  } catch (error) {
    console.error("Error initializing data:", error);
    return { success: false, error };
  }
}

Then call the server action from the layout component after session verification

student/Layout.tsx

import type { Metadata } from "next";
import "../globals.css";
import Sidebar from "@/app/components/templates/sidebar";
import {
  Home,
  Calendar,
  BookOpenText,
  LibraryBig,
  ClipboardList,
  Waypoints,
} from "lucide-react";
import { Montserrat } from "next/font/google";
import { fetchServerSession } from "../backend/lib/hooks/getServerSession";
import { redirect } from "next/navigation";
import { initializeData } from "./actions";

const montserrat = Montserrat({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default async function RootLayout({
  children,
}: Readonly<{
  children: React.ReactNode;
}>) {
  const session = await fetchServerSession();

  if (!session?.user) {
    redirect("/");
  }

  // Initialize data using the server action
  await initializeData(session.user.school_id, session.user.id);

  const navigationItems = [
    {
      name: "Dashboard",
      href: "/student/dashboard",
      icon: <Home />,
      current: true,
    },
    {
      name: "Calendar",
      href: "/student/calendar",
      icon: <Calendar />,
      current: false,
    },
    {
      name: "Classes",
      href: `/student/classes`,
      icon: <BookOpenText />,
      current: false,
    },
    {
      name: "Study Material",
      href: "/student/studyMaterial",
      icon: <LibraryBig />,
      current: false,
    },
    {
      name: "Tests & Assignments",
      href: "/student/tests+assignments",
      icon: <ClipboardList />,
      current: false,
    },
    {
      name: "Learning Paths",
      href: "/student/learningPaths",
      icon: <Waypoints />,
      current: true,
    },
  ];

  return (
    <html lang="en" className="h-full bg-gray-100">
      <body className={`${montserrat.className} antialiased bg-lightBg`}>
        <Sidebar navigation={navigationItems} />
        <main className="py-10 lg:pl-72">
          <div className="px-4 sm:px-6 lg:px-8">{children}</div>
        </main>
      </body>
    </html>
  );
}

Let me know if you get any issues

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742388922a4434622.html

相关推荐

  • next.js - Next JS 14 Setting Cookie In Layout - Stack Overflow

    Im trying to fetch and essentially cache the data using cookies, but I'm getting an error when cre

    15小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信