cookies() methods
- cookies().get(‘cookie_name’): It will return cookies as an object with name and value.
- cookies().getAll(): It will returns an array object of all cookies returned with name and value.
- cookies().has(‘cookie_name’): It will return a Boolean value based on whether the cookie exists (true) or not (false).
- cookies().set(name, value, options): It is used to set the cookie.
- cookies().delete(‘cookie_name’): It is used to delete the cookie.
Creating 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
cookies in Next JS
Next.js provides a cookies function that allows 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.
Syntax:
import { cookies } from 'next/headers'
function MyComponent() {
const cookieStore = cookies()
const name = cookieStore.get('cookie_name').value;
return (
...
);
}