Using API client
How to use API client to interact with the API.
In Next.js, you can access the API client in two ways:
- server-side: in server components and API routes
- client-side: in client components
When you create a new page and want to fetch some data, Server Components are the perfect place where to fetch it: it is done when you render your page (which means one less round-trip) and the data is streamed to the client (so it's very fast).
In Next.js, every component is a Server Component, unless you specify use client
, which converts it to a client component. Client components are also server-rendered, however they're also rendered on the client. Server Components are only rendered on the server - so we can use data-fetching methods (using Supabase, in our case) and fetch all the required data for a particular layout or page.
We'll go through both options to see its differences and how to use them.
Server-side
We're creating a server-side API client inside apps/web/src/lib/api/server.ts
file. It involves doing a few things such as:
- creating a tRPC context
- caching query client
- setting up the auth client for accessing user session
- initializing
api
client from tRPC
It's all set up and ready to use, so you shouldn't be worried about anything else than calling the API.
Then, there is nothing simpler to just call the API from your server component:
Next.js - Server components
nextjs.org
Client-side
We're creating a separate client-side API client in apps/web/src/lib/api/react.tsx
file. It's a simple wrapper around the @tanstack/react-query that fetches or mutates data from the API.
It also requires wrapping your app in a TRPCReactProvider
component to provide the API client to the rest of the app:
Of course, it's all already configured for you, so you just need to start using api
in your client components:
Next.js - Client components
nextjs.org
Ensure correct API url
Inside the apps/web/src/lib/api/shared.ts
we're calling a function to get base url of your api, so make sure it's set correctly (especially on production) and your api endpoint is corresponding with the name there.
As you can see we're mostly relying on the environment variables to get it, so there shouldn't be any issues with it, but in case, please be aware where to find it 😉
Last updated on