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?