404 Not Found Next.js error on React-Query fetch

Viewed 1902

Here is my situation. I am trying to set up a Next.js project with an Express.js back-end. I did set up the back-end as a regular one not as a custom server according to Next.js documentation. So I am not sure if I am already making a mistake by setting up the back-end as a regular one. I am trying to fetch data from a back-end endpoint http://localhost:3500/api/v1/list using axios and it works well. But when I am trying to implement React-Query on the first load I am getting the right data from the back-end but when it is trying to re-fetch for some reason it is hitting the wrong end-point http://localhost:3600/api/v1/list and getting the 404 Not Found error. It looks like it is switching the port from 3500 to 3600 which is a front-end port. Here you will find the link to the repository and here is the code. Let me know if I am doing something wrong,

page/sell.js

import axios from 'axios';
import { useQuery } from 'react-query';

export default function SellPage({ response }) {
  const { data, isLoading, error } = useQuery('sells', getPosts, {
    initialData: response,
  });

  console.log('data useQuery: ', data);

  if (isLoading) return 'Loading...';
  if (error) return error.message;
  return (
    <div>
      <p>Hello SellPage!!{data.message}</p>
    </div>
  );
}

export async function getServerSideProps(context) {
  const response = await getPosts();
  console.log('response', response);
  if (!response) {
    return {
      notFound: true,
    };
  }

  return {
    props: { response }, // will be passed to the page component as props
  };
}

async function getPosts() {
  console.log('HOST: ', process.env.HOST);
  const { data } = await axios.request({
    baseURL: process.env.HOST,
    url: '/api/v1/list',
    method: 'get',
  });
  return data;
}

_app.js

import React from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import { ReactQueryDevtools } from 'react-query/devtools';

const queryClient = new QueryClient();

function MyApp({ Component, pageProps }) {
  const queryClientRef = React.useRef();
  if (!queryClientRef.current) {
    queryClientRef.current = new QueryClient();
  }
  return (
    <>
      <QueryClientProvider client={queryClientRef.current}>
        <Component {...pageProps} />
        <ReactQueryDevtools initialIsOpen={false} />
      </QueryClientProvider>
    </>
  );
}

export default MyApp;
2 Answers

I don't see a next.config.js in your repo, so I guess the env variables are not bundled in the js and in the end you url looks like localhost: or localhost:undefined which the browser default to the port your client is served.

Try add next.config.js

module.exports = {
  env: {
    HOST: process.env.HOST,
  },
}

SEE: https://nextjs.org/docs/api-reference/next.config.js/environment-variables

Another way is to use public runtime variables

module.exports = {
  publicRuntimeConfig: {
    // Will be available on both server and client
    port: 3500,
  },
};

// Then
import getConfig from 'next/config';

// Only holds serverRuntimeConfig and publicRuntimeConfig
const { publicRuntimeConfig } = getConfig();
console.log(publicRuntimeConfig.port);

SEE: https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration

But note that runtime config would impact optimization and you might get larger bundle in the end so you might want to try build time variables first.

if you get 404 i think that you reached out the server but no API's name matched so try to test the API first on postman or alike however if console.log('HOST: ', process.env.HOST); prints http://localhost:3600 then do the following in your .env file try to rename PORT TO SERVER_PORT or whatever

HOSTNAME=localhost
SERVER_PORT=3500
HOST=http://$HOSTNAME:$SERVER_PORT

i'm not sure but maybe ur frontend serve bash hold PORT env val as 3600

Related