Creating a Route to Fetch Notes in Our CloudNoteBook App ๐๏ธ๐
So far in our CloudNoteBook App, we've set up user signup and login with JWT
authentication. But a notes app isn't very useful if users can't actually see their
notes! In this part of the React JS tutorial for beginners, we'll create a
protected backend route that fetches all notes belonging to the logged-in user.
In this tutorial, we will learn:
- Why fetching notes needs to be a protected (authenticated) route
- Setting up
express.Router()insideroutes/notes.js - Using the
fetchusermiddleware to identify the logged-in user - Writing a
GETroute to fetch only that user's notes from MongoDB - Handling errors gracefully with
try/catch - Testing the route with Postman before connecting it to React
Why Do We Need a Protected Route to Fetch Notes?
Every user of CloudNoteBook should only see their own notes โ not notes
belonging to other users. That means our fetch notes route can't simply return
everything in the database. Instead, it must first verify who is making the request
using the JWT token sent in the request header, and then query MongoDB for notes that
belong to that specific user's ID.
Step 1: Set Up the Router and Import Dependencies
Open (or create) routes/notes.js and import express, our Notes
model, and the fetchuser middleware we built earlier for authentication.
const express = require("express");
const router = express.Router();
const Notes = require("../models/Notes");
const fetchuser = require("../middleware/fetchuser");
module.exports = router;
Step 2: Understand the fetchuser Middleware
The fetchuser middleware reads the JWT token from the request header, verifies it,
and attaches the decoded user info to req.user. This is what lets our route know
which user is asking for their notes.
// middleware/fetchuser.js (already created in a previous step)
var jwt = require("jsonwebtoken");
const JWT_SECRET = "cloudnotebook$ecret";
const fetchuser = (req, res, next) => {
const token = req.header("auth-token");
if (!token) {
return res.status(401).send({ error: "Please authenticate using a valid token" });
}
try {
const data = jwt.verify(token, JWT_SECRET);
req.user = data.user;
next();
} catch (error) {
res.status(401).send({ error: "Please authenticate using a valid token" });
}
};
module.exports = fetchuser;
Step 3: Write the Route to Fetch All Notes
Now let's add a GET route at /api/notes/fetchallnotes. We pass
fetchuser as a middleware before our route handler โ this ensures the route
only runs for authenticated requests. Inside, we use Notes.find() to fetch
only the notes where user matches req.user.id.
// ROUTE 1: Fetch all notes of a logged-in user using GET "/api/notes/fetchallnotes"
router.get("/fetchallnotes", fetchuser, async (req, res) => {
try {
const notes = await Notes.find({ user: req.user.id });
res.json(notes);
} catch (error) {
console.error(error.message);
res.status(500).send("Internal Server Error");
}
});
Step 4: Test the Route Using Postman
Before connecting this route to our React frontend, let's confirm it works on its own.
GET http://localhost:5000/api/notes/fetchallnotes
Headers:
auth-token: <paste the JWT token received at login>
Expected Response (200 OK):
[
{
"_id": "6710a9f3c2a1b2d3e4f5a6b7",
"user": "6710a1b2c3d4e5f6a7b8c9d0",
"title": "Grocery List",
"description": "Milk, eggs, bread",
"tag": "personal",
"date": "2026-10-01T10:15:00.000Z"
}
]
If the auth-token header is missing or invalid, the route correctly responds
with a 401 Unauthorized error instead of leaking any notes.
Step 5: Full Updated notes.js Route File
Here is the complete routes/notes.js file with our fetch-notes route in place.
const express = require("express");
const router = express.Router();
const Notes = require("../models/Notes");
const fetchuser = require("../middleware/fetchuser");
// ROUTE 1: Fetch all notes of a logged-in user using GET "/api/notes/fetchallnotes"
router.get("/fetchallnotes", fetchuser, async (req, res) => {
try {
const notes = await Notes.find({ user: req.user.id });
res.json(notes);
} catch (error) {
console.error(error.message);
res.status(500).send("Internal Server Error");
}
});
module.exports = router;
Route Summary at a Glance
| Method | Endpoint | Auth Required | Description |
|---|---|---|---|
GET |
/api/notes/fetchallnotes |
Yes (auth-token header) |
Returns all notes belonging to the logged-in user only |
Features and Learnings:-
express.Router() inside routes/notes.js.fetchuser middleware to protect the route with JWT.GET /api/notes/fetchallnotes route using Notes.find().try/catch.auth-token header.