Để lưu token vào cookie trong Next.js, bạn có thể sử dụng các API server-side của Next.js như getServerSideProps hoặc API Routes để set cookie trên phía server. Ngoài ra, bạn có thể sử dụng JavaScript trên phía client để set cookie nếu cần.
Dưới đây là hướng dẫn cơ bản về cách lưu token vào cookie trong Next.js:
Khi bạn sử dụng API Routes của Next.js, bạn có thể set cookie từ phía server bằng cách sử dụng header Set-Cookie.
// pages/api/login.js import cookie from 'cookie'; export default function handler(req, res) { if (req.method === 'POST') { const { token } = req.body; // Set cookie res.setHeader('Set-Cookie', cookie.serialize('token', token, { httpOnly: true, // Bảo mật, không thể truy cập từ JavaScript phía client secure: process.env.NODE_ENV !== 'development', // Chỉ dùng HTTPS ở production maxAge: 60 * 60 * 24, // Cookie sẽ hết hạn sau 1 ngày sameSite: 'strict', // Chỉ gửi cookie với yêu cầu cùng site path: '/', // Áp dụng cho toàn bộ trang web })); res.status(200).json({ message: 'Token đã được lưu vào cookie' }); } else { res.status(405).json({ message: 'Method Not Allowed' }); } }
Sau khi token được lưu vào cookie từ server, bạn có thể truy cập nó từ các API server-side trong Next.js như getServerSideProps hoặc getInitialProps.
// pages/profile.js import { parse } from 'cookie'; export async function getServerSideProps({ req }) { const cookies = parse(req.headers.cookie || ''); const token = cookies.token || null; return { props: { token }, // Truyền token vào component dưới dạng props }; } export default function ProfilePage({ token }) { return ( <div> <h1>Profile Page</h1> {token ? <p>Token: {token}</p> : <p>Bạn chưa đăng nhập</p>} </div> ); }
Nếu bạn muốn lưu token từ phía client, bạn có thể sử dụng thư viện như js-cookie để thao tác với cookie trong JavaScript.
npm install js-cookie
import Cookies from 'js-cookie'; function login(token) { Cookies.set('token', token, { expires: 1, secure: true, sameSite: 'Strict' }); } function logout() { Cookies.remove('token'); }
Đây là cách cơ bản để lưu và quản lý token trong cookie khi làm việc với Next.js.
Leave A Comment