Making API Requests in Next.js Firebase
Learn how to make requests to your Next.js Firebase API in Makerkit
To make requests to the API functions in the api folder, we provide a custom hook useApiRequest, a wrapper around fetch.
It has the following functionality:
- Automatically adds a
Firebase AppCheck Tokento the request headers if you enabled Firebase AppCheck - Automatically adds a
CSRF tokento the request headers
We use this in conjunction with the swr to simplify its usage using React components.
src/core/hooks/use-create-session.ts
import useApiRequest from '~/core/hooks/use-api';interface Body { idToken: string;}export function useCreateSession() { const endpoint = '/api/session/sign-in'; const fetcher = useApiRequest<void, Body>(); return useSWRMutation(endpoint, (path, { arg }) => { return fetcher({ path, body: arg, }); });}You can use this hook in your components:
import { useCreateSession } from '~/core/hooks/use-create-session';function Component() { const { trigger, ...mutationState } = useCreateSession(); return ( <> { mutationState.isMutating ? `Mutating...` : null } { mutationState.error ? `Error :(` : null } { mutationState.data ? `Yay, success!` : null } <SignInForm onSignIn={(idToken) => trigger({ idToken })} /> </> );}