Next.js Discord

Discord Forum

Rewrites not working for Server Side component

Unanswered
Northeast Congo Lion posted this in #help-forum
Open in Discord
Avatar
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
joulev
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 this
export function fetchBackend(url, options) {
  return fetch(`http://localhost:3000${url}`, options);
}
Avatar
Northeast Congo LionOP
Thanks!