Skip to content

API Calls

Fresh

Source: shipfa.st/docs/tutorials/api-call

Any file named route.js in the /app/api folder is an API endpoint. Use the helper /libs/api.js (axios instance) for simplified API calls.

API Client Features

  • Automatically displays error messages
  • Redirects to login page on 401 errors
  • Adds /api as base URL: /api/user/posts becomes /user/posts

Frontend Example (Protected API Call)

javascript
"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;

Backend Example (Protected Route)

javascript
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 {
    return NextResponse.json({ error: "Not signed in" }, { status: 401 });
  }
}

WARNING

You must configure the database before making database queries.

See Also