API Routes

Learn how to create and manage API routes in your Next.js application.

Makerkit provides some utilities to reduce the boilerplate needed to write Next.js API functions. This section will teach you everything you need to know to write your API functions.

Calling API functions from the client

In Next.js App Router, the API functions are defined using the special file conventions named route.ts. You can add these anywhere in your app directory.

When the API functions are "standalone" and not tied to a specific page, it makes sense to add them to app/api.

First, we define a function using the utility useApiRequest and SWR's useSWRMutation hook.

import useSWRMutation from 'swr/mutation'; import configuration from '~/configuration'; import useApiRequest from '~/core/hooks/use-api'; import useRefresh from '~/core/hooks/use-refresh'; interface Params { membershipId: number; } const path = configuration.paths.api.organizations.transferOwnership; function useTransferOrganizationOwnership() { const fetcher = useApiRequest<void, Params>(); const refresh = useRefresh(); const key = ['organizations', 'transfer-ownership']; return useSWRMutation( key, (_, { arg }: { arg: Params }) => { return fetcher({ path, method: `PUT`, body: { membershipId: arg.membershipId, }, }); }, { onSuccess: refresh, } ); } export default useTransferOrganizationOwnership;

Then, we can define a route function in the file app/api/organizations/owner/route.ts.

export async function PUT(req: Request) { // logic to transfer ownership }

Sending the CSRF Token

When you use the hook useApiRequest, you don't need to worry about sending the CSRF token. The hook will automatically send the token.

Instead, if you use fetch directly, you need to send the CSRF token. To retrieve the page's CSRF token, you can use the useCsrfToken hook:

const csrfToken = useCsrfToken(); console.log(csrfToken) // token

You will need to send a header x-csrf-token with the value returned by useCsrfToken().

CSRF Token check

The middleware will automatically check that the CSRF Token is present and is valid in the request header for requests that require it.

API Logging

The boilerplate uses Pino for API logging, a lightweight logging utility for Node.js.

Logging is necessary to debug your applications and understand what happens when things don't behave as expected. You will find various instances of logging throughout the API, but we encourage you to log more if necessary.

We import the logging utility from ~/core/logger. Typically, you can log every time you perform an action, both before and after. For example:

async function myFunction(params: { organizationId: string; userId: string; }) { logger.info( { organizationId: params.organizationId, userId: params.userId, }, `Performing action...` ); await performAction(); logger.info( { organizationId: params.organizationId, userId: params.userId, }, `Action successful` ); }

It's always important to add context to your logs: as you can see, we use the first parameter to add important information.


Subscribe to our Newsletter
Get the latest updates about React, Remix, Next.js, Firebase, Supabase and Tailwind CSS