#fetch with external api + cookies
1 messages · Page 1 of 1 (latest)
Hi @plush fiber. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
When you're making a fetch request to an external API and want to include cookies, you can use the credentials: 'include' option in your fetch request. This will automatically include cookies for the current domain in the request. However, this will only work if the server responds with the Access-Control-Allow-Credentials: true header and the request is made to the same domain.
Here's an example of how you can do this:
fetch('<https://example.com',> {
credentials: 'include',
})
However, if you're making requests to an external server from a Next.js server-side function (like an API Route or a Server Component), the cookies from the client's browser won't automatically be included. This is because the request is being made from the server, not from the client's browser.
In this case, you'll need to manually include the cookies in your request. You can get the cookies from the request object in your server-side function, and then include them in your fetch request to the external API.
Here's an example of how you can do this in an API Route:
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const auth = req.cookies.authorization
const response = await fetch('<https://example.com',> {
headers: {
'Authorization': `Bearer ${auth}`,
},
})
// ...
}
In this example, the authorization cookie is retrieved from the request object and included in the Authorization header of the fetch request to the external API.
Remember that this is just an example, and the actual implementation will depend on how your external API expects to receive the cookies.
Sources:
- Next.js Docs: Reading cookies (https://nextjs.org/docs/pages/building-your-application/data-fetching/forms-and-mutations#reading-cookies)
- Next.js Docs: Accessing Request Object (https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration#accessing-request-object)
- Github Issue: cannot got cookies in route handler (https://github.com/vercel/next.js/issues/60552)
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@plush fiber kapa.ai is still learning and improving, please let us know how it did by reacting below
@dull sky It'll work if localhost:3000 is the nextjs frontend and localhost:8081 is the fastify backend?
Let me check the knowledge base for you. One moment! :books:
If you're running your Next.js frontend on localhost:3000 and your Fastify backend on localhost:8081, you can still make fetch requests from the frontend to the backend. However, because these are different domains, you'll run into issues with CORS (Cross-Origin Resource Sharing) and cookies.
For CORS, you'll need to configure your Fastify server to accept requests from localhost:3000. You can do this using the fastify-cors plugin. Here's an example:
// On your Fastify server
fastify.register(require('fastify-cors'), {
origin: '<http://localhost:3000',>
credentials: true
})
For cookies, the credentials: 'include' option in your fetch request will not work across different domains. This is a security feature of browsers to prevent CSRF attacks.
Instead, you'll need to manually include the cookies in your request. You can get the cookies from the request object in your server-side function, and then include them in your fetch request to the Fastify server.
Here's an example of how you can do this in an API Route:
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const auth = req.cookies.authorization
const response = await fetch('<http://localhost:8081',> {
headers: {
'Authorization': `Bearer ${auth}`,
},
})
// ...
}
In this example, the authorization cookie is retrieved from the request object and included in the Authorization header of the fetch request to the Fastify server.
Remember that this is just an example, and the actual implementation will depend on how your Fastify server expects to receive the cookies.
Sources:
- Next.js Docs: Reading cookies (https://nextjs.org/docs/pages/building-your-application/data-fetching/forms-and-mutations#reading-cookies)
- Next.js Docs: Accessing Request Object (https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration#accessing-request-object)
- Github Issue: cannot got cookies in route handler (https://github.com/vercel/next.js/issues/60552)
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@plush fiber kapa.ai is still learning and improving, please let us know how it did by reacting below
@dull sky Is it possible I can directly do the fetch post within the app page ie /@profile will fetch user data
Let me check the knowledge base for you. One moment! :books:
Yes, you can fetch data directly within a page in Next.js. This can be done either on the server-side or on the client-side.
For server-side data fetching, you can use the getServerSideProps function in your page. This function runs on the server-side every time the page is requested. Here's an example:
// pages/@profile.js
export async function getServerSideProps({ req, query }) {
const authHeader = req.getHeaders()['authorization'];
const response = await fetch('<http://localhost:8081',> {
headers: {
'Authorization': `Bearer ${authHeader}`,
},
});
const data = await response.json();
return { props: { data } };
}
export default function ProfilePage({ data }) {
// Render your page with the data
}
In this example, the getServerSideProps function fetches data from the Fastify server and passes it as a prop to the page component.
For client-side data fetching, you can use the useEffect hook in your page component. This hook runs after the component has been rendered on the client-side. Here's an example:
// pages/@profile.js
import { useState, useEffect } from 'react';
export default function ProfilePage() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('<http://localhost:8081'>)
.then((res) => res.json())
.then((data) => setData(data));
}, []);
// Render your page with the data
}
In this example, the useEffect hook fetches data from the Fastify server after the page has been rendered on the client-side.
Remember that these are just examples, and the actual implementation will depend on your specific requirements.
Sources:
- Next.js Docs: Data Fetching (https://nextjs.org/docs/basic-features/data-fetching)
- Next.js Docs: Accessing Request Object (https://nextjs.org/docs/app/building-your-application/upgrading/app-router-migration#accessing-request-object)