API

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:

page.tsx
import { api } from "~/lib/api/server";
 
export default async function MyServerComponent() {
  const posts = await api.posts.getAll();
 
  /* do something with the data... */
  return <div>{JSON.stringify(posts)}</div>;
}

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:

layout.tsx
export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html lang="en">
      <body>
        <TRPCReactProvider>{children}</TRPCReactProvider>
      </body>
    </html>
  );
}

Of course, it's all already configured for you, so you just need to start using api in your client components:

page.tsx
"use client";
 
import { api } from "~/lib/api/react";
 
export default function MyClientComponent() {
  const { data: posts, isLoading } = api.posts.getAll.useQuery();
 
  if (isLoading) {
    return <div>Loading...</div>;
  }
 
  /* do something with the data... */
  return <div>{JSON.stringify(posts)}</div>;
}

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.

shared.ts
const getBaseUrl = () => {
  if (typeof window !== "undefined") return window.location.origin;
  if (env.NEXT_PUBLIC_SITE_URL) return env.NEXT_PUBLIC_SITE_URL;
  if (env.VERCEL_URL) return `https://${env.VERCEL_URL}`;
  return `http://localhost:${process.env.PORT ?? 3000}`;
};
 
export const getUrl = () => {
  return getBaseUrl() + "/api/trpc";
};

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

On this page

Ship your startup everywhere. In minutes.Get TurboStarter