Horje
cookies in Next JS

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:

Next.js Cookies – FAQs

How do I set a cookie in Next.js?

Next.js provide built-in cookies methods. cookies().set() is used to set name, value and other options in cookies.

How can I read cookies in Next.js?

We can use cookies().get(name_of_cookie) to read the value.

How do I delete a cookie in Next.js?

cookies().delete(name_of_cookie) deletes a cookie with the provided name.

How to make cookie auto expire?

We can provide maxAge and epires values in option while seting a cookie.




Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
useRouter in Next JS useRouter in Next JS
Next JS 13 App Router Next JS 13 App Router
How does JSX differ from HTML ? How does JSX differ from HTML ?
Find the Minimum Distance Between Two Numbers in PHP Find the Minimum Distance Between Two Numbers in PHP
How to Find the Smallest of given Two Nnumbers In PHP ? How to Find the Smallest of given Two Nnumbers In PHP ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
11