Open In App

cookies in Next JS

Last Updated : 25 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Next.js provides cookies methods that allow you to store small pieces of data on the client side. It provides methods to store, delete, components and retrieve the cookie. cookies function can only used in server components. To store and delete the cookie at the client side using the cookies function you can only store and delete the cookie by using Server Action or Route Handler.

Next.js Cookies

Cookies in Next.js are used for storing data on the client side, such as user preferences or session information. They enable persistent state and enhance user experiences across different sessions.

Note: Cookies methods are introduced in Next.js version 13

Syntax:

import { cookies } from 'next/headers'

function MyComponent() {

const cookieStore = cookies()
const name = cookieStore.get('cookie_name').value;

return (
...
);
}

cookies methods

Method Description
cookies().get('cookie_name')Returns the cookie as an object with name and value.
cookies().getAll()Returns an array of all cookies, each with name and value.
cookies().has('cookie_name')Returns a Boolean indicating if the cookie exists (true) or not (false).
cookies().set(name, value, options)Sets a cookie with the specified name, value, and optional settings.
cookies().delete('cookie_name')Deletes the cookie with the specified name.

Steps to Create Next.js Application

Step 1: Create a Next.js application using the following command.

npx create-next-app@latest gfg

Step 2: After creating your project folder i.e. gfg, move to it using the following command.

cd gfg

Project Structure:

cookie-project-structure

Implementing Cookies in Next.js

In this example, we are using Server Action to store and delete the cookies and display it on server component. we have defined the cookie store and delete function at server component and passing this functions to the client component through props and we will make the action from client component through Form(button) submit.

Note: Remove the included css file from layout.js file.

Example: The below example demonstrates the use of Cookies functions in nextjs.

JavaScript
// File path: src/app/page.js

import { cookies } from "next/headers";
import AddCookiebtn from "@/app/Actionbutton";

export default async function Home() {
	// Fetching the 'name' cookie value or setting a default value
	const cookieStore = cookies();
	const name = cookieStore.get("name")
		? cookieStore.get("name").value
		: "set the cookie";

	// Async function to create a 'name' cookie
	async function createCookie() {
		"use server";
		cookies().set("name", "GeeksForGeeks");
	}

	// Async function to delete the 'name' cookie
	async function deleteCookie() {
		"use server";
		cookies().delete("name");
	}

	return (
		<div>
			<h1>GeeksForGeeks | Cookie Example</h1>
			<h2>Cookie value: {name}</h2>
			{/* Rendering the AddCookiebtn component and 
				passing create and delete functions as a props */}
			<AddCookiebtn create={createCookie} delete={deleteCookie} />
		</div>
	);
}
JavaScript
//File path: src/app/Actionbutton.js

// 'use client' indicates that this is client component
'use client';

const Page = (props) => {
	return (
		<>
			{/* Form for setting a cookie */}
			<form action={props.create}>
				<button type="submit">Set Cookie</button>
			</form>

			<br />

			{/* Form for deleting a cookie */}
			<form action={props.delete}>
				<button type="submit">Delete Cookie</button>
			</form>
		</>
	);
}

export default Page;

To run the Application open the terminal in the project folder and enter the following command:

npm run dev

Output:


Similar Reads