ℹ️
Any file named route.ts
in the /app/api
folder is an API endpoint. Use the helper /libs/api.ts
•Automatically display error messages
•Redirect to login page upon error 401
• Add /api
as a base url:/users/posts
Protected Api Calls
Supabase automatically handles the authentification with cookies. Just make a normal API call on the front-end like this:
/app/user-profile/page.ts
"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.ts
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 });
}
}