Skip to content

🌐 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 });
  }
}