Design Converter
Education
Developer Advocate
Last updated on Jul 3, 2024
Last updated on May 14, 2024
Cookies are a fundamental part of web development, serving as a reliable mechanism for session management, storing user preferences, and much more. In the context of Next.js, a cutting-edge framework for building server-rendered React applications, understanding how to manage cookies is crucial for creating secure, efficient, and user-friendly web applications. In this blog, you'll learn about the intricacies of handling Next.js cookies, from setting and retrieving them to ensuring they work seamlessly across both the client and server sides.
Before diving into the technicalities, let's clarify what cookies are. Cookies are small pieces of data stored on the client's browser. They are sent back and forth between the client and the server with each request, allowing the server to recognize users across multiple requests. In Next.js, cookies play a vital role in server-side rendering, API routes, and overall state management.
In Next.js, you can manage cookies on both the server-side and the client side. Server-side cookies are set and read during server actions, such as when server components render or within API routes. Client-side cookies, on the other hand, are managed directly within the browser by client components.
1// Setting a cookie on the server side 2res.setHeader('Set-Cookie', 'token=1234; Path=/; HttpOnly'); 3 4// Reading a cookie on the client side 5const token = document.cookie.replace(/(?:(?:^|.*;\s*)token\s*=\s*([^;]*).*$)|^.*$/, "$1"); 6
When you use server components or server-side rendering in Next.js, you'll often need to manage cookies as part of your server actions. This involves setting, reading, and deleting cookies based on the incoming requests and outgoing responses.
To set cookies on the server side, you'll typically modify the Set-Cookie header of the outgoing response. This can be done within API routes or in server components that handle server actions.
1export default function handler(req, res) { 2 res.setHeader('Set-Cookie', 'sessionId=abc123; Path=/; HttpOnly'); 3 res.status(200).json({ message: 'Cookie set' }); 4}
When you need to access cookies that come with the incoming request, you can use the req.headers.cookie property. This is particularly useful in route handlers where you need to tailor the return response based on user data.
1export default function handler(req, res) { 2 const cookies = req.headers.cookie; 3 // Parse the cookies and use them in your server action 4}
To delete cookies, you set the cookie with an empty value and a past expiration date. This tells the browser to remove the cookie immediately.
1export default function handler(req, res) { 2 res.setHeader('Set-Cookie', 'sessionId=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT'); 3 res.status(200).json({ message: 'Cookie deleted' }); 4}
While server-side cookies are essential for secure operations like authentication, client-side cookies are useful for less sensitive data, such as user preferences or UI state.
On the client side, you can use JavaScript to set, get, and delete cookies. The document.cookie property provides a simple interface for cookie management.
1// Setting a cookie on the client side 2document.cookie = 'theme=dark; Path=/;'; 3 4// Deleting a cookie on the client side 5document.cookie = 'theme=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT';
For more complex scenarios, you might want to use a library like js-cookie to simplify cookie management on the client side.
1import Cookies from 'js-cookie'; 2 3// Setting a cookie using js-cookie 4Cookies.set('user', 'John Doe', { expires: 7, path: '' }); 5 6// Getting a cookie value using js-cookie 7const user = Cookies.get('user');
Next.js offers advanced techniques for handling cookies, especially when dealing with server-side rendering and API routes.
Middleware in Next.js allows you to run code before a request is completed. This is a perfect place to manage cookies, especially for operations that need to happen on every request.
1// This middleware will run before every request in the pages directory 2export function middleware(req) { 3 const { cookies } = req; 4 // Perform operations with cookies here 5} 6 7// Example: Adding a default cookie if one doesn't exist 8if (!cookies.get('defaultSetting')) { 9 cookies.set('defaultSetting', 'lightMode', { path: '/' }); 10}
In the above code snippet, the middleware checks if a defaultSetting cookie exists. If it does not, the middleware sets a new cookie with a key of defaultSetting and a value of lightMode. This ensures that every incoming request has access to this default setting, providing a consistent experience across the application.
HTTPOnly cookies are a critical security feature that helps mitigate the risk of client-side script attacks, such as cross-site scripting (XSS). By marking a cookie as HTTPOnly, you instruct the browser to prevent client-side access to the cookie, ensuring that it can only be sent to the server with HTTP requests.
In Next.js, setting HTTPOnly cookies is a straightforward process that involves modifying the Set-Cookie header within your server actions. This is typically done in route handlers or API routes where you have control over the outgoing response headers.
1// Setting an HTTPOnly cookie in a Next.js API route 2export default function handler(req, res) { 3 res.setHeader('Set-Cookie', 'authToken=secret; Path=/; HttpOnly'); 4 res.status(200).json({ message: 'HTTPOnly cookie set successfully' }); 5}
In the code example above, an HTTPOnly cookie named authToken is being set with a value of secret. The Path=/ attribute specifies that the cookie is accessible for all paths on the domain, and the HttpOnly attribute ensures that the cookie cannot be accessed through JavaScript running in the browser.
It's important to note that while HTTPOnly cookies enhance security by protecting against certain types of attacks, they are not a silver bullet. You should still implement other security measures, such as validating and sanitizing all user inputs, to provide a comprehensive defense against security threats.
When using HTTPOnly cookies in your Next.js application, always ensure that you are setting them in a secure context, preferably with the Secure attribute alongside HttpOnly. This ensures that the cookies are only sent over HTTPS, further protecting the data from potential eavesdroppers.
When you have multiple cookies to manage, it's important to ensure that your multiple cookies match the correct scenarios. For instance, you might have different cookies for authentication, user preferences, and session tracking.
1// Setting multiple cookies 2res.setHeader('Set-Cookie', [ 3 'authToken=secret; Path=/; HttpOnly', 4 'userPreferences=dark; Path=/', 5 'sessionTracking=active; Path=/' 6]);
Setting expires and path attributes correctly is crucial for cookie management. The expires attribute determines how long the cookie should live, while the path attribute specifies the URL path the cookie is valid for.
1// Setting a cookie with an expiration date and path 2const expiryDate = new Date(); 3expiryDate.setDate(expiryDate.getDate() + 7); // Expires in 7 days 4res.setHeader('Set-Cookie', `userSettings=dark; Expires=${expiryDate.toUTCString()}; Path=/`);
Next.js provides a robust set of features that work hand-in-hand with cookies to create dynamic and responsive web applications.
Server-side rendering in Next.js can leverage cookies to personalize the rendered content based on user data. When a page is requested, the server can read the cookies from the incoming request and use them to fetch data or modify the response accordingly.
1// Example of SSR with cookies in Next.js 2export async function getServerSideProps({ req }) { 3 const cookies = req.headers.cookie; 4 // Use cookies to fetch user-specific data 5 return { props: { /* ... */ } }; 6}
API routes in Next.js are server-side routes where you can handle incoming requests and outgoing responses, including cookie operations. They are defined in .js files within the /pages/api directory.
1// Example of an API route that sets a cookie 2export default function handler(req, res) { 3 res.setHeader('Set-Cookie', 'apiToken=12345; Path=/; HttpOnly'); 4 res.status(200).json({ success: true }); 5}
The Next.js app router and pages router can be used to navigate between pages while maintaining cookie integrity. When navigating, any cookies set on the server will be included in the request headers, ensuring a consistent user experience.
1// Navigating with Next.js router while preserving cookies 2import { useRouter } from 'next/router'; 3 4const router = useRouter(); 5 6// Function to navigate to the home page 7function goToHomePage() { 8 router.push('/home'); 9}
To ensure that you manage cookies effectively in your Next.js applications, follow these best practices:
Secure Your Cookies: Always set the HttpOnly, Secure, and SameSite attributes to prevent cross-site scripting (XSS) and cross-site request forgery (CSRF) attacks.
Minimize Cookie Size: Store only essential information in cookies to reduce the overhead on each request.
Use Middleware Wisely: Implement middleware for common cookie operations that need to run across multiple routes.
Handle Cookie Parsing: When dealing with raw req.headers.cookie values, use a reliable parsing method to handle multiple cookies, and extract the first match correctly.
Consider User Privacy: Inform users about your cookie policy and provide options to manage their cookie preferences.
Cookies are a powerful tool in web development, and mastering their use in Next.js is essential for building modern, full-featured web applications. By understanding how to set, read, and delete cookies on both the server and client sides, and by integrating them with Next.js' robust features, you can create applications that are functional, secure, and user-friendly.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.