We created an API route
to fetch the products from the CMS
and return the same data
but stripping out the fields we don't need.
Now we want to call that API route
from the client side.
And this approach will be a variant
of what we called "Option 2".
Let's rename this existing page "2a".
So this is where we fetch products
on the client side,
but directly from an external API,
that in our case is the CMS.
Now I'm going to create
another copy of this page,
and this will be "Option 2b",
that is about fetching the data
from an internal API route.
Ok. In this case instead of calling "getProducts",
that as we know calls the CMS,
we want to "fetch" the data from our API route,
that is "/api/products".
And note that here we don't need
to specify the host and port
because the API route will always run
on the same server as this page.
Fetch returns an asynchronous response,
so we need to use "await",
but here we have a small problem in that
we cannot make this function "async",
because "useEffect" doesn't accept a function
that returns a Promise.
As a workaround we can create
an anonymous async function here,
and immediately invoke it.
Then move this code inside it,
so this block will be "async".
Next, we want to get the "products"
by parsing the response as JSON.
And at this point we can update
the value of the state variable.
Ok. Let's see if this works.
We need to load our new page "2b".
And it looks all right,
we can see the usual six products.
But let's see what happens in the server logs
when we load this page.
You can see that our "/api/products" handler
is called right after the HomePage is rendered.
And this happens every time we load the page.
Now, let's go and inspect the Network requests.
Here we can see that it requested
"/api/products" on "localhost" port 3000.
And if we look at the data
each product only has "id" and "title".
If we look at the response headers
we should be able to see
the exact size of the data.
It's just 192 bytes, as shown by
the "Content-Length" header.
Out of curiosity I want to see
what's the difference compared to our "Option 2a",
that is when we call the CMS API directly.
In this case the "Content-Length" is
9,363 bytes.
So by fetching the data via an API route
we reduced the size of the data sent to the browser
from over 9,000 bytes to just 192.
This should give you an idea of why
creating an API route may be worth it,
even though it's a bit of extra work.
With this, we have now seen all possible ways
to fetch data in a Next.js application.
And in the next video we'll review them
and choose the best one for our specific use case.