Mastering Cookies in Next.js: A Comprehensive Guide
Understanding Cookies
Cookies are small pieces of data stored on a user’s browser, containing information such as user preferences, session IDs, or tracking data. They can be created by both client-side and server-side operations. Server-side cookies are typically created and accessed via HTTP headers, while client-side cookies are created using JavaScript.
Client-Side vs. Server-Side Cookies
While both types of cookies are stored on the user’s browser, there’s a key difference between them. Client-side cookies can be accessed directly by JavaScript, whereas server-side cookies with the httpOnly attribute enabled cannot be accessed by JavaScript, reducing the risk of XSS attacks.
Handling Cookies in Server Components
Next.js provides a built-in way to handle cookies in server components using the cookies
object.
Getting Cookies
To read incoming request cookie values, use the cookies.get(cookieName)
method:
import { cookies } from 'next/cookies';
function HomePage() {
const userId = cookies.get('user_id');
if (!userId) {
return <p>No user ID found</p>;
}
return <p>User ID: {userId}</p>;
}
Setting Cookies
To set new cookies, use the cookies.set()
method. Note that this method can only be used in Server Actions or API routes:
import { cookies } from 'next/cookies';
function SetCookiePage() {
const theme = 'dark';
cookies.set('theme', theme);
return <p>Cookie set successfully!</p>;
}
Deleting Cookies
To delete cookies, use the cookies.delete(name)
method. Like setting cookies, this method can only be used in Server Actions or API routes:
import { cookies } from 'next/cookies';
function DeleteCookiePage() {
cookies.delete('theme');
return <p>Cookie deleted successfully!</p>;
}
Handling Cookies in Middleware
In Next.js, middleware functions can access and modify cookies using the req
and res
objects. To get a cookie, use req.cookies.get(cookieName)
, and to set a cookie, use res.cookie(name, value)
.
Getting Cookies in Middleware
import { NextApiRequest, NextApiResponse } from 'next';
const middleware = async (req: NextApiRequest, res: NextApiResponse) => {
const userId = req.cookies.get('user_id');
if (!userId) {
return res.status(401).json({ error: 'Unauthorized' });
}
return next();
};
Setting Cookies in Middleware
import { NextApiRequest, NextApiResponse } from 'next';
const middleware = async (req: NextApiRequest, res: NextApiResponse) => {
const theme = 'dark';
res.cookie('theme', theme);
return next();
};
Using Cookie Packages in Next.js
There are several packages available to help manage cookies in Next.js. Two popular options are react-cookie and cookies-next.
Using react-cookie
react-cookie provides a simple way to load and save cookies within your React application. To get started, install the package and import it in your pages:
npm install react-cookie
import { useCookies } from 'eact-cookie';
function HomePage() {
const [cookies, setCookie] = useCookies(['user_id']);
const userId = cookies.user_id;
return <p>User ID: {userId}</p>;
}
Using cookies-next
cookies-next is a lightweight package specifically designed for Next.js. It provides a simple way to set and get cookies on both the client-side and server-side.
Note: The usage of cookies-next will be similar to the built-in cookies
object.