Any file named route.js in the /app/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
Protected API calls
1. API call:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 "use client" import { useState } from "react"; const UserProfile = () => { const [isLoading, setIsLoading] = useState(false); const remindUser = async (to: string, subject: string, text: string) => { setIsLoading(true); try { const { data } = await fetch('/send-email', { to, subject, text })); console.log(data); } catch (e) { console.error(e?.message); } finally { setIsLoading(false); } }; return ( <button className="btn btn-primary" onClick={() => remindUser('john@gmail.com', 'Hello', 'This email is ...')}> {isLoading && ( <span className="loading loading-spinner loading-sm"></span> )} Save </button> ); }; export default UserProfile;
2. 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 import { sendEmail } from '@/utils/mailgun'; export default async function handler(req: any, res: any) { if (req.method === 'POST') { const { to, subject, text } = req.body; try { const result = await sendEmail(to, subject, text); res.status(200).json({ success: true, result }); } catch (error) { res.status(500).json({ success: false, error: (error as Error).message }); } } else { res.status(405).json({ message: 'Method Not Allowed' }); } }