Rewrites not working for Server Side component
Unanswered
Northeast Congo Lion posted this in #help-forum
![Avatar](https://cdn.discordapp.com/embed/avatars/0.png)
Northeast Congo LionOP
async function getData() {
const res = await fetch('/api/user/')
// The return value is *not* serialized
// You can return Date, Map, Set, etc.
if (!res.ok) {
// This will activate the closest `error.js` Error Boundary
throw new Error('Failed to fetch data')
}
return res.json()
}
export default async function Page() {
const data = await getData()
return <main></main>
}
module.exports = {
async rewrites() {
return [
{
source: '/api/:path*',
destination: 'http://localhost:5000/api/:path*', // Proxy to Backend
},
];
},
reactStrictMode: false,
transpilePackages: ['ui'],
};
I'm trying to run a rewrite to reach my external API, but it doesn't seem to work unless I run it as a client component. It seems that the rewrite does not work on the server side
2 Replies
![Avatar](https://cdn.discordapp.com/embed/avatars/0.png)
@Northeast Congo Lion ts
async function getData() {
const res = await fetch('/api/user/')
// The return value is *not* serialized
// You can return Date, Map, Set, etc.
if (!res.ok) {
// This will activate the closest `error.js` Error Boundary
throw new Error('Failed to fetch data')
}
return res.json()
}
export default async function Page() {
const data = await getData()
return <main></main>
}
ts
module.exports = {
async rewrites() {
return [
{
source: '/api/:path*',
destination: 'http://localhost:5000/api/:path*', // Proxy to Backend
},
];
},
reactStrictMode: false,
transpilePackages: ['ui'],
};
I'm trying to run a rewrite to reach my external API, but it doesn't seem to work unless I run it as a client component. It seems that the rewrite does not work on the server side
![Avatar](https://cdn.discordapp.com/avatars/484037068239142956/1f8b69b2fc7b58b174c04d0b43498b3a.webp?size=256)
the reason is that the server doesn't know its own origin, so all http requests from the server must have the full URL: you must use
await fetch("http://localhost:3000/api/user")
for the fetch to work. BUT that statement is still bad as [it can cause your build to fail if you try to statically render the page](https://nextjs-discord-common-questions.joulev.dev/fetching-own-api-endpoint-in-react-server-components). Instead I suggest just make a fetch() wrapper and prepend localhost:5000
to it. Something like thisexport function fetchBackend(url, options) {
return fetch(`http://localhost:3000${url}`, options);
}
![Avatar](https://cdn.discordapp.com/embed/avatars/0.png)
Northeast Congo LionOP
Thanks!