TutorialsAPI call
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
- Add /api as a base URL: /api/user/posts → /user/posts
Protected API calls
NextAuth automatically handles the authentication with cookies. Just make a normal API call on the front-end like this:
/app/user-profile/page.js
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:
/app/api/user/route.js