Adding API Routes

API Routes allow you to create server endpoints in your Remix App that you can call from your client or from external sources

API routes are a way to create a custom API endpoint for your application. You can use API routes to create RESTful endpoints that return JSON data.

Adding an API route to a Makerkit application is no different than any other Remix project. Let's see how.

Creating an API Route

To create an API route, will export an action function from your routes.

Here's an example of an API route that returns a JSON response as response to a GET request.

import { json } from "@remix-run/node"; export async function loader() { return json({ text: 'Hello' }); }

This is kinda simple, right? Let's see how we can use this API route in our application.

Protecting API Routes

It's very likely that you want to ensure only authenticated users can access your API routes. To do that, you can use the requireSession function.

In the example below, we create a POST API route that requires the user to be authenticated. If the user is not authenticated, the user will be redirected away. Additionally, the requireSession function will also ensure the level access if the user opted in to multi factor authentication.

import { LoaderFunctionArgs } from "@remix-run/node"; import getSupabaseServerClient from '~/core/supabase/server-client'; import requireSession from '~/lib/user/require-session.server'; export async function loader(args: LoaderFunctionArgs) { const client = getSupabaseServerClient(args.request); const session = await requireSession(client); // user is authenticated, do something here }

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