In my code, I have a function that can be called either from server-side rendering or client side:
export const getData = async (): Promise<any> => {
const response = await fetch(`/data`, {
method: 'GET',
headers: CONTENT_TYPE_JSON,
})
if (!response.ok) {
//handle error
}
//continue processing data
}
If this function is called from the server:
export const getServerSideProps: GetServerSideProps = async () => {
getData().then(() => {
//do something
})
}
An error occurs because it's not an absolute URL. One solution is to create a similar function with a different URI:
export const getData = async (): Promise<any> => {
const response = await fetch(`http://myapp/data`, {
method: 'GET',
headers: CONTENT_TYPE_JSON,
})
if (!response.ok) {
//handle error
}
//continue processing data
}
Another option is to pass a prefix URL argument to getData
.
Is there a more generic way to dynamically add the absolute URL part when calling from server-side rendering?