In this article, we will discuss in detail Next Js Cookies management and how we can handle cookies at Client-Side or Serveri-Side in the Next js application with examples. We will explore what are its advantages, use cases and best practices to make their usage more secure and optimal.
[lwptoc]
What are Cookies, and Why Do We Need Them?
Cookies are small pieces of data stored on a user’s device by the web browser. These play an important role in the world of the internet due to following reasons:
State Management: Cookies help us to maintain a stateful information bridge between various HTTP requests especially when dealing with the user session and authentication.
Personalization: Cookies can be saved on the user’s browser to be consumed for providing personalized experiences on websites by remembering user preferences and settings for example advertising industry.
Tracking and Analytics: User behaviour plays a key role which can be easily tracked to provide valuable insights to know how users interact with a website.
Remembering User Information: Various kinds of user information like usernames, language preferences, or items in a shopping cart can also be persisted into Cookies to later usage.
Why Use Cookies in a Next.js Application?
The Next js applications which can be rendered client side or server side, cookies provide several advantages:
Server Side (SSR) and Client Side Render (CSR) Compatibility: Cookies can work seamlessly with both rendering approaches, to ensure consistent state management in the entire application. We will see later in this guide on using cookies for both approaches with examples.
Lightweight and Scalable: Cookies are lightweight and can handle various types of data which makes them a scalable choice for managing client-side state.
Client-Side Persistence: Cookies help to persist the data state between page visits and browser sessions to enhance the user experience.
Cross-Origin Support: Cookies support various attributes which allow them to be shared across different subdomains, making them an excellent choice for handling authentication tokens across multiple related domains.
Setting Up Next.js with Cookies
Let’s set up a new Next.js application by executing the below create next app command:
npx create-next-app@11 my-cookie-app
cd my-cookie-app
Install Required Dependencies
Next, to work with cookies in a Next.js project, we need to install the universal-cookie
package. Install it using npm. It provides a simple and easy to use API for setting, getting, and removing cookies which works both on the server and client side.
npm install cookie universal-cookie
How to Set and Get cookies in Next.js?
We can use the universal-cookie
package to set and get cookies in Next.js. Here’s an example of how to set a cookie:
import { Cookies } from 'universal-cookie';
const cookies = new Cookies();
// Set a cookie with name 'myCookie' and value 'hello' that expires in 1 day
cookies.set('myCookie', 'hello', { maxAge: 86400 });
And here’s how you can get the value of a cookie:
const cookieValue = cookies.get('myCookie');
console.log(cookieValue); // Output: 'hello'
How to delete cookies in Next.js?
To delete cookies in Next.js, use the remove
method from universal-cookie
:
// Remove the 'myCookie' cookie
cookies.remove('myCookie');
Options and Attributes for Setting Cookies
The universal-cookie
provides a number of attributes to customize the behaviour of the cookie. Following are some common attributes to include:
maxAge : To handle cookie expiration, we can set the maxAge
or expires
attribute when setting the cookie. The cookie will automatically be deleted when the specified time or date has passed. This value is in seconds.
expires : The expiration date to determine how long the cookie remains valid.
path : The URL path where the cookie is valid.
domain : The domain where the cookie is valid, to share a cookie across all subdomains of example.com
, set the domain attribute to .example.com
// Set a cookie that is accessible across all subdomains of 'example.com'
cookies.set('sharedCookie', 'value', { domain: '.example.com' });
secure : The secure
attribute ensures the cookie is only sent over HTTPS connections.
httpOnly : To enhance cookie security in Next.js, we can set the httpOnly
and secure
attributes when setting the cookie. The httpOnly
attribute prevents client-side access to the cookie.
// Example of setting a cookie with various attributes
cookies.set('myCookie', 'hello', {
maxAge: 86400,
path: '/',
domain: 'example.com',
secure: true,
httpOnly: true,
});
How to Set and Get Cookies on Client Side and Server Side in Next Js Application?
We will discuss working examples of setting and getting the values of Cookies in Next js application on both Client-Side and Server-Side:
Next.js fully supports server-side rendering (SSR) and client-side rendering (CSR). Cookies work seamlessly with both rendering approaches. When using SSR, you can set cookies on the server side, and when using CSR, you can access and manipulate cookies on the client side.
Difference between Server-side and client-side cookies?
In server-side, cookies are set and accessed on the server side which is mainly during server-side rendering or API routes. They are used for tasks like session management and setting initial client-side state.
Client-side cookies, are set and accessed on the client side and that is usually through JavaScript. They are ideal for managing state which needs to persist across page visits or browser sessions.
Setting and Getting Cookies on the Client Side using universal-cookie:
Create a new component called CookieExample.js
in the components
folder:
import React, { useState } from 'react';
import { Cookies } from 'universal-cookie';
const cookies = new Cookies();
const CookieExample = () => {
const [inputValue, setInputValue] = useState('');
const handleSetCookie = () => {
cookies.set('myCookie', inputValue, { path: '/' });
setInputValue('');
};
const handleGetCookie = () => {
const cookieValue = cookies.get('myCookie');
alert(`Cookie value: ${cookieValue}`);
};
return (
<div>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder="Enter cookie value"
/>
<button onClick={handleSetCookie}>Set Cookie</button>
<button onClick={handleGetCookie}>Get Cookie</button>
</div>
);
};
export default CookieExample;
Use the CookieExample
component in a page (pages/index.js
):
import React from 'react';
import CookieExample from '../components/CookieExample';
const HomePage = () => {
return (
<div>
<h1>Welcome to My Cookie App</h1>
<CookieExample />
</div>
);
};
export default HomePage;
In the above example, when we enter a value in the input field and click “Set Cookie,” it will set a cookie named myCookie
with the entered value. Clicking “Get Cookie” will retrieve the value of the cookie and show an alert with the cookie value.
Setting and Getting Cookies on the Server Side using cookies package:
Next.js API routes allow you to handle server-side logic, which we can use for setting and getting cookies. The cookies
package provides an easy way to work with cookies on the server side.
Create an API route (pages/api/cookies.js
):
import { parse, serialize } from 'cookie';
export default function handler(req, res) {
if (req.method === 'POST') {
// Set a cookie on the server-side
const { myCookie } = req.body;
res.setHeader('Set-Cookie', serialize('myCookie', myCookie, { path: '/' }));
res.status(200).json({ message: 'Cookie set successfully!' });
} else if (req.method === 'GET') {
// Get a cookie from the request object on the server-side
const cookies = parse(req.headers.cookie || '');
const myCookieValue = cookies.myCookie || 'Cookie not set';
res.status(200).json({ cookieValue: myCookieValue });
} else {
res.status(405).end(); // Method Not Allowed
}
}
Then use the API route on the client-side (components/ServerCookieExample.js
):
import React, { useState } from 'react';
const ServerCookieExample = () => {
const [inputValue, setInputValue] = useState('');
const handleSetCookie = async () => {
const response = await fetch('/api/cookies', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ myCookie: inputValue }),
});
const data = await response.json();
alert(data.message);
setInputValue('');
};
const handleGetCookie = async () => {
const response = await fetch('/api/cookies');
const data = await response.json();
alert(`Cookie value on server-side: ${data.cookieValue}`);
};
return (
<div>
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder="Enter cookie value"
/>
<button onClick={handleSetCookie}>Set Cookie (Server-side)</button>
<button onClick={handleGetCookie}>Get Cookie (Server-side)</button>
</div>
);
};
export default ServerCookieExample;
Use the ServerCookieExample
component in a page (pages/index.js
):
import React from 'react';
import ServerCookieExample from '../components/ServerCookieExample';
const HomePage = () => {
return (
<div>
<h1>Welcome to My Cookie App</h1>
<ServerCookieExample />
</div>
);
};
export default HomePage;
Now when we enter a value in the input field and click “Set Cookie (Server-side),” it will set a cookie named myCookie
with the entered value on the server-side.
Then clicking “Get Cookie (Server-side)” will retrieve the value of the cookie from the server-side and show an alert with the cookie value.
These examples demonstrate how to set and get cookies on both the client-side and server-side in Next.js using different packages like universal-cookie
for client-side and cookies
package for server-side.
Make sure when using cookies on the server-side, we should ensure the appropriate security measures, like setting httpOnly
and secure
attributes.
Run Next Js App
Now you can run the Nexgt js app by executing below command:
npm run dev
Open your browser and go to http://localhost:3000
.
Conclusion
We discussed how to work with Cookies in Next js application. By using the universal cookies and cookies packages we can easily manage the type of cookies we want to create and also set, get or remove them using the provided API methods.
We also discussed how to easily manage cookies from Client side or Server side Next js application with examples. Hope this was helpful
Leave a Reply