Need a custom feature? We can help!

API

API Routes Overview

StartupFast comes with predefined API routes that are used for handling payments, sending emails, and a todos API that demonstrates different patterns for handling requests. Routes are located in the /app/api directory, following the Next.js 14 conventions.

Similarly to pages, each folder under the api folder corresponds to an API endpoint, and the definition of the endpoint is contained in the route.ts file. You can refer to the Next.js documentation for more information about API endpoints.

NOTE: Make sure you have your database and authentication set up.

Protected Routes

Protected routes are routes that require authentication. StartupFast comes with some handy utilities that will determine if a user is authenticated and if they are a premium user, meaning they have an active subscription or have bought your product.

Protected Route Example

The Todos API in your boilerplate demonstrates how to check if a user is authenticated (/app/api/todos/route.ts).

1export const GET = async function GET(): Promise<
2  NextResponse<GetTodoResponse | { message: string }>
3> {
4  /* This block of code is going to retrieve the user from the database and return 401 if the user is not authenticated */
5  const user = await getCurrentUser();
6  if (!user) {
7    return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
8  }
9  const { data, error } = await supabase
10    .from("Todo")
11    .select("*")
12    .eq("user_id", user.id);
13  if (!data || error) {
14    return NextResponse.json(
15      { message: "No todo list found" },
16      { status: 404 }
17    );
18  }
19  const res: GetTodoResponse = { todos: data };
20  return NextResponse.json(res, { status: 200 });
21};

Calling the API Endpoint from Your Components

To make an API call from your client components, you simply need to fetch your endpoints. For example, this component is fetching the GET endpoint of the todos API: /components/todos-client/todos-client.tsx

1const fetchTodos = () => {
2  setIsLoading(true);
3  setError(null);
4  fetch("/api/todos")
5    .then((res) => res.json())
6    .then((data) => {
7      ///...
8    })
9    .catch((error) => setError(error.message))
10    .finally(() => setIsLoading(false));
11};