logoBuildBox

API call

There are 2 built-in ways to authenticate users with ShipFast Magic Links & Google Oauth.

Any file named route.js in the /app/api folder is an API endpoint. Use the helper /libs/api.js (axios instance with interceptors) to simplify API calls:

  • Automatically display error messages
  • Redirect to login page upon error 401
  • Add /api as a base URL: /api/user/posts → /user/posts

Protected API calls

Supabase automatically handles the authentication with cookies. Just make a normal API call on the front-end like this:

/app/user-profile/page.tsx
"use client"
 
import { useState } from "react";
import apiClient from "@/libs/api";
 
const UserProfile = () => {
  const [isLoading, setIsLoading] = useState(false);
 
  const saveUser = async () => {
    setIsLoading(true);
 
    try {
      const { data } = await apiClient.post("/user", {
        email: "new@gmail.com",
      });
 
      console.log(data);
    } catch (e) {
      console.error(e?.message);
    } finally {
      setIsLoading(false);
    }
  };
 
  return (
    <button className="btn btn-primary" onClick={() => saveUser()}>
      {isLoading && (
        <span className="loading loading-spinner loading-sm"></span>
      )}
      Save
    </button>
  );
};
 
export default UserProfile;

In the backend, we get the session and we can use it to retrieve the user from the database. You have to configure the database first. The API file should look like this:

/app/api/user/route.js
import { createRouteHandlerClient } from "@supabase/auth-helpers-nextjs";
import { NextResponse } from "next/server";
import { cookies } from "next/headers";
 
export const dynamic = "force-dynamic";
 
export async function POST(req) {
  const supabase = createRouteHandlerClient({ cookies });
  const { data } = await supabase.auth.getSession();
  const { session } = data;
 
  if (session) {
    const body = await req.json();
 
    if (!body.email) {
      return NextResponse.json({ error: "Email is required" }, { status: 400 });
    }
 
    try {
      // This call will fail if you haven't created a table named "users" in your database
      const { data } = await supabase
        .from("users")
        .insert({ email: body.email })
        .select();
 
      return NextResponse.json({ data }, { status: 200 });
    } catch (e) {
      console.error(e);
      return NextResponse.json(
        { error: "Something went wrong" },
        { status: 500 }
      );
    }
  } else {
    // Not Signed in
    NextResponse.json({ error: "Not signed in" }, { status: 401 });
  }
}

Last updated on

On this page

Edit on GitHub