admin管理员组文章数量:1335386
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 badges1 Answer
Reset to default 0The 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
本文标签: nextjsNext JS 14 Setting Cookie In LayoutStack Overflow
版权声明:本文标题:next.js - Next JS 14 Setting Cookie In Layout - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742388921a2465598.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论