getServerSideProps does not render dynamic pages in production, and show 404 error

1.2k Views Asked by At

I'm working with next.js, in development mode everything works fine, but in production mode I have a problem when rendering the pages dynamically. I have the following path inside the pages folder pages/user/[id], and this component is where I call the getServerSideProps function.


import headers from '../../headers';

export async function getServerSideProps(context) {

  const URL = 'https://somewhere...';

  let { id } = context.params;

  const apiResponse = await fetch(
    `${URL}/${id}/detail`,
    {
      headers: headers,
    }
  ); 
  if (apiResponse.ok) {
    
    const data = await apiResponse.json();
    return {
      props: data, // will be passed to the page component as props
    };
  } else {   
    return { props: {} };
  }
  
}

My problem is the following, I need to send in headers the authentication token that I only get when I login and I get the 2FA code, so in build time, that info does not exist and I get a 401 error no authorizate when execute npm run build and when I access to /user/34 for example I get a 404 error.

I have checked these questions at stackoverflow:

I have some parts in my app that are statics and works fine, but the problem is with the dynamic paths, as next.js is not creating those paths.

EDIT: I'll include a image with other problem, if after the fetch in the if I just say :

if(apiResponse){ //without 'ok'

}

I'll recieve this errror: response error

1

There are 1 best solutions below

1
On
return {
      props: data, // will be passed to the page component as props
    }

props should be object

return {
          props: {data} // or props: {data:data}
        }