乐闻世界logo
搜索文章和话题

How to include cookies with fetch request in Nextjs

1个答案

1

In Next.js, if you need to make requests on the server side and include cookies from the user, it's important to understand that requests can be initiated in two distinct environments: client-side (browser) and server-side.

Client-Side Requests

When making requests on the client side (e.g., within the useEffect hook or event handling functions), cookies are typically sent automatically with the request as long as it targets the same origin or CORS policies are correctly configured to allow credentials. For example, you can use the fetch API:

javascript
fetch('https://your-api-domain.com/path', { method: 'GET', // or 'POST', 'PUT', etc. credentials: 'include', // ensure cookies are included }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));

The credentials: 'include' option ensures cookies are included even for cross-origin requests. For same-origin requests, using credentials: 'same-origin' is sufficient.

Server-Side Requests

On the Next.js server side (e.g., in getServerSideProps or getInitialProps), requests do not automatically include cookies because these functions run on the server and cannot access browser cookies directly. Therefore, you must manually extract cookies from the request headers and attach them to the server-side request headers.

Here's an example of including cookies in getServerSideProps:

javascript
export async function getServerSideProps(context) { const { req } = context; const cookies = req.headers.cookie; const res = await fetch('https://your-api-domain.com/path', { method: 'GET', headers: { // Manually set cookies cookie: cookies || '' }, credentials: 'include' // Required for cross-origin requests }); const data = await res.json(); // Return props return { props: { data }, // Pass data as props to the page }; }

In this example, we first retrieve cookies sent from the browser via the request context (context.req), then set these cookies in the request headers when making the server-side API request.

Note: When handling cookies, ensure security considerations are taken into account—do not expose sensitive information in insecure environments—and adhere to relevant HTTP specifications and best practices.

2024年6月29日 12:07 回复

你的答案