fetching data
Unanswered
Exotic Shorthair posted this in #help-forum
Exotic ShorthairOP
can I fetch in a next.js server component like this? to handle both local and prod instances?
i am getting this error though it does exist on the backend
const response = await fetch('/api/companies')
i am getting this error though it does exist on the backend
Error fetching companies: [TypeError: Failed to parse URL from /api/companies] {
[cause]: [TypeError: Invalid URL] {
code: 'ERR_INVALID_URL',
input: '/api/companies'
}
}
5 Replies
@Exotic Shorthair can I fetch in a next.js server component like this? to handle both local and prod instances?
const response = await fetch('/api/companies')
i am getting this error though it does exist on the backend
Error fetching companies: [TypeError: Failed to parse URL from /api/companies] {
[cause]: [TypeError: Invalid URL] {
code: 'ERR_INVALID_URL',
input: '/api/companies'
}
}
Brown bear
you can use fetch in server components but it requires a fully qualified url ("https://website.com/api")
If you want to reuse some logic then you can export a function somewhere and have the api route and the server component call it
Asian black bear
Having to use a fully qualified URL to your own server, assuming it's not a separate backend, is indicative of you doing it wrong. Basically don't fetch your own server in server-side code: https://nextjs-faq.com/fetch-api-in-rsc
@Asian black bear Having to use a fully qualified URL to your own server, assuming it's not a separate backend, is indicative of you doing it wrong. Basically don't fetch your own server in server-side code: https://nextjs-faq.com/fetch-api-in-rsc
Exotic ShorthairOP
i appreciate the feedback but I did not have access to the database in my project.
I had access to a production API hosted on retool.
I had access to a production API hosted on retool.
I think my case falls in your assumption that, it is a seperate backend