TutorialsAPI call

Any file in the /pages/api/ folder is an API endpoint. Use the helper /libs/api.js (axios instance with interceptors) to simplify API calls:

  • Automatically display error messages
  • Redirect to login page upon error 401
  • Add /api as a base URL: /api/user/posts /user/posts

Protected API calls

NextAuth automatically handles the authentification part. Just make a normal API call on the front-end like this:

user-profile.js

1import { useState } from "react";
2import apiClient from "@/libs/api";
3
4const UserProfile = () => {
5  const [isLoading, setIsLoading] = useState(false);
6
7  const saveUser = async () => {
8    setIsLoading(true);
9
10    try {
11      const { data } = await apiClient.post("/user", {
12        email: "new@gmail.com",
13      });
14
15      console.log(data);
16    } catch (e) {
17      console.error(e?.message);
18    } finally {
19      setIsLoading(false);
20    }
21  };
22
23  return (
24    <button className="btn btn-primary" onClick={() => saveUser()}>
25      {isLoading && (
26        <span className="loading loading-spinner loading-sm"></span>
27      )}
28      Save
29    </button>
30  );
31};
32
33export default UserProfile;
34

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:

/api/user.js

1import { getServerSession } from "next-auth/next";
2import { authOptions } from "../auth/[...nextauth]";
3import connectMongo from "@/libs/mongoose";
4import User from "@/models/User";
5
6export default async function handler(req, res) {
7  const session = await getServerSession(req, res, authOptions);
8
9  if (session) {
10    await connectMongo();
11
12    const { id } = session.user;
13    const { method, body } = req;
14
15    switch (method) {
16      case "POST": {
17        if (!body.email) {
18          return res.status(404).send({ error: "Email is needed" });
19        }
20
21        try {
22          const user = await User.findById(id);
23
24          if (!user) {
25            return res.status(404).json({ error: "User doesnt exists" });
26          }
27
28          user.email = body.email;
29          await user.save();
30
31          return res.status(200).json({ data: user });
32        } catch (e) {
33          console.error(e);
34          return res.status(500).json({ error: e?.message });
35        }
36      }
37
38      default:
39        res.status(404).json({ error: "Unknow request type" });
40    }
41  } else {
42    // Not Signed in
43    res.status(401).end();
44  }
45}
46