ℹ️
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 { NextResponse } from "next/server";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/libs/next-auth";
import connectMongo from "@/libs/mongoose";
import User from "@/models/User";
export async function POST(req) {
const session = await getServerSession(authOptions);
if (session) {
await connectMongo();
const { id } = session.user;
const body = await req.json();
if (!body.email) {
return NextResponse.json({ error: "Email is required" }, { status: 400 });
}
try {
const user = await User.findById(id);
if (!user) {
return NextResponse.json({ error: "User not found" }, { status: 404 });
}
user.email = body.email;
await user.save();
return NextResponse.json({ data: user }, { 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 });
}
}