π Working with API¶
π API Handling¶
Each file named route.js
inside the /app/api
folder represents an API endpoint.
You can use the helper file /libs/api.js
(which is a pre-configured instance of axios
with interceptors) to simplify your API requests. It automatically does the following:
- Displays error messages
- Redirects to the login page on a
401 Unauthorized
error - Automatically prefixes requests with
/api
π Example: instead of /api/user/posts
you can simply use /user/posts
.
Example: user/posts/
β /api/user/posts
π Securing Sensitive API Requests¶
β NextAuth handles authentication automatically using cookies.
// /app/user-profile/page.js
"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;
π₯οΈ On the Backend¶
On the backend, you can retrieve the session and use it to fetch the userβs data from the database. Make sure your database is configured first.
Hereβs what your API file would look like:
// /app/api/user/route.js
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) {
const { id } = session.user;
const body = await req.json();
if (!body.email) {
return NextResponse.json({ error: "Email is required" }, { status: 400 });
}
try {
await connectMongo();
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
return NextResponse.json({ error: "Not signed in" }, { status: 401 });
}
}