1

I have a NextJS project with express backend that requires some data fetching in getServerSideProps.

The problem is await fetch('/api/anyApi') does not work with relative path and calls to absolute path await fetch('${config.OPTION_HOST}/api/anyApi' are getting blocked by some kind of protection on host machine.

I wish to fix this problem instead and just use absolute paths but I've been told that's not possible right now so I need to rewrite getServerSideProps everywhere to not use fetch.

Best solution I could find without rewriting big chunk of backend logic was to use mocks like in this anwser.

So instead of const result = await fetch('/api/menu/${context.locale}'), I ended up with this code:

export async function getServerSideProps(context) {
  
  const categoryController = require('../../../server/controllers/category')
  
  var MockExpressRequest = require('mock-express-request');
  var MockExpressResponse = require('mock-express-response');

  var requestMenu = new MockExpressRequest( {
    params: {
      locale: context.locale,
    }
  })
  var responseMenu = new MockExpressResponse();

  await categoryController.getCategories(requestMenu, responseMenu);

  const result = responseMenu

...rest of getServerSideProps...
}

I'm new to programing and while this solution works, I have a feeling that using a library for testing in production code might be bad idea. What do you think?

AndrewL64
  • 15,794
  • 8
  • 47
  • 79
Bodya
  • 13
  • 3
  • That's not a problem with `fetch`. You shouldn't be fetching data from an internal API route inside `getServerSideProps`. Instead, use the logic that's in your API route directly in `getServerSideProps`. See [Internal API fetch with getServerSideProps? (Next.js)](https://stackoverflow.com/questions/65752932/internal-api-fetch-with-getserversideprops-next-js). – juliomalves Aug 08 '22 at 09:38

1 Answers1

0

You could use AXIOS instead: https://www.npmjs.com/package/axios

You can find all the AXIOS documentation here: https://axios-http.com/

Hammad Ahmad
  • 184
  • 1
  • 6