0

Hello im going to get data from API using this https://nextjs.org/docs/basic-features/data-fetching/get-server-side-props

but I'm using Axios instead of default like doc, same as the doc passing data through the props, already implement this but instead return data its return 500 internal server which is it works when on the localhost.

this is my home.js

import axios from "axios";
import Featured from "../components/Featured";
import ProductList from "../components/ProductList";
import styles from "../styles/Home.module.css";

export default function Home({ productList }) {
  return (
    <div className={styles.container}>
      <Featured />
      <ProductList productList={productList} />
    </div>
  );
}

export const getServerSideProps = async () => {
  const res = await axios.get(
    "http://localhost:3000/api/products" ||
      "https://marrs-id.vercel.app/api/products"
  );
  const data = await res.data;
  return {
    props: {
      productList: data,
    },
  };
};

enter image description here

enter image description here

am I missing something here?

  • What error are you seeing on Vercel logs? – juliomalves Apr 26 '22 at 12:55
  • Also, you shouldn't be calling an internal API route from inside `getServerSideProps`, use the API logic directly. See [Internal API fetch with getServerSideProps? (Next.js)](https://stackoverflow.com/questions/65752932/internal-api-fetch-with-getserversideprops-next-js). – juliomalves Apr 26 '22 at 12:57

1 Answers1

0

You might want to store your API path in a .env file at the root of your project. So it can be used everywhere in your app and easy to maintain ? Also I guess you can use Fetch instead of Axios for this case, something like this :

export const getServerSideProps = async () => {
  const productListRes = await fetch(
    `${process.env.API_ROOT}/api/products`
  );
  const productList = await productListRes.json();
  return {
    props: {
      productList,
    },
  };
};
zharkan
  • 1
  • 2