Setting cookies in Next.js 14 typically involves both server-side (e.g., in API routes) and client-side scenarios. Here are the methods for setting cookies in these scenarios:
1. Setting Cookies on the Server (e.g., in API Routes)
Setting cookies on the server is commonly used for scenarios such as setting session cookies after authentication. You can utilize the Node.js http module or third-party libraries like cookie and js-cookie to assist with cookie management. Here, we demonstrate using the cookie library to set cookies in API routes:
First, install the cookie library:
bashnpm install cookie
Then, set cookies in Next.js API routes as follows:
javascript// pages/api/set-cookie.js import { serialize } from 'cookie'; export default function handler(req, res) { const cookie = serialize('myCookie', 'cookieValue', { httpOnly: true, secure: process.env.NODE_ENV !== 'development', maxAge: 60 * 60 * 24 * 7, // 1 week path: '/', }); res.setHeader('Set-Cookie', cookie); res.status(200).json({ message: 'Cookie has been set' }); }
2. Setting Cookies on the Client
Setting cookies on the client is typically used for storing non-sensitive information in the user's browser. You can simplify client-side cookie operations using the js-cookie library. First, install js-cookie:
bashnpm install js-cookie
Then, set cookies in client-side code as follows:
javascriptimport Cookies from 'js-cookie'; function setClientCookie() { Cookies.set('clientCookie', 'clientValue', { expires: 7, path: '' }); }
This function can be invoked in any client-side event or React component, such as when a user clicks a button.
Summary
When using Next.js, choose between server-side or client-side cookie setting based on your specific requirements (e.g., whether sensitive information is involved or server-side rendering is needed). Always prioritize security by using options like httpOnly and secure to enhance application security.