Fetching to the internal API (relative API path) on the Next.js App Router

The text discusses how to fetch the internal API on the Next.js App Router. It highlights the difference between the Next.js Page Router and the App Router in terms of calling the internal REST API. It mentions that using the fetch function with a relative path will result in an error, and suggests setting the fetch target URL as a full URL. The text also describes how to retrieve the domain and host on the application using the next/headers library. It provides an example code snippet that demonstrates fetching the API with the full URL. Finally, it mentions that in the Next.js App Router, the request header information such as the protocol and host can be obtained using the next/headers library.

広告ここから
広告ここまで

目次

    I noted the way to fetch the internal API on the Next.js App Router.

    Difference of the Next.js Page Router

    Before App Router (Page Router), we can call the internal REST API by using fetch function like fetch('/api/xxx').

    But in the case of the App Router, we will get the following error.

    Unhandled Runtime Error
    Error: Failed to parse URL from /api/prices

    We need to set the fetch target URL as a full URL instead of a relative path.

    Retrieve the domain and its host on the application using next/headers

    I tried to get the full URL using next/headers library like the following code:

    import { Metadata } from 'next'
    import { headers } from 'next/headers'
    export const metadata: Metadata = {
      title: 'Products',
    }
    export default async function Page() {
        const headersData = headers()
        const host = headersData.get('host')
        const protocol = headersData.get('x-forwarded-proto') ?? host.startWith('localhost') ? 'http' : 'https' 
        const apiBase = `${protocol}://${host}`
        const res = await fetch(`${apiBase}/api/prices`, {
            next: {
                revalidate: 10 * 60 // 10 minutes
            }
        }).then(data => data.json())
    ...

    In the Next.js App Router, we can get the request header information like the protocol and the host using next/headers.

    Referrence

    広告ここから
    広告ここまで

    Random posts

    Home
    Search
    Bookmark