Build a REST API with Express 5
By the end of this lesson NoteNest will have a working REST API: it lists notes, filters them by tag, returns one note and creates new ones, always in JSON and always with the error shape you agreed on. You will also connect the Vue client to it through Vite's proxy and lock the API down with a CORS allow-list. Notes are kept in memory for now; the next lesson moves them into MongoDB without changing the API.
What you should know first: Project Structure for MEVN Apps, because every file here goes into that layout. If routes and middleware are new to you, read Express 5 Basics, Middleware and Building a REST API first. Version checked: Express 5.3.0 on Node.js, with cors 2.8.6 and helmet 8.3.0.
REST in one paragraph
A REST API organises a server around resources (things, such as notes) with one URL each, and uses the HTTP method to say what to do. GET /api/notes reads the list, POST /api/notes adds to it, GET /api/notes/42 reads one item. The status code in the response says how it went: 200 OK, 201 Created, 400 bad input, 404 not found.
It works like a railway reservation counter. The counter number tells you the service (resource), and the form you fill tells the clerk what you want (method). The clerk always answers on the same printed slip format, whether the ticket was booked or the train was full. Our printed slip is JSON.
This lesson builds three routes:
| Method and path | Success | Possible errors |
|---|---|---|
GET /api/notes?tag=home | 200 with { notes } | none |
GET /api/notes/:id | 200 with { note } | 404 NOT_FOUND |
POST /api/notes | 201 with { note } | 400 VALIDATION_ERROR or BAD_REQUEST |
Editing and deleting come in CRUD Endpoints & Validation.
Step 1: Build the app in app.js
Replace the test server from the set-up lesson with the split from the structure lesson. app.js builds the app and exports it:
// server/src/app.js
import express from 'express'
import cors from 'cors'
import helmet from 'helmet'
import { config } from './config.js'
import notesRouter from './routes/notes.js'
import { notFound, errorHandler } from './middleware/errors.js'
const app = express()
app.use(helmet())
app.use(cors({ origin: config.clientOrigins }))
app.use(express.json({ limit: '100kb' }))
app.get('/api/health', (req, res) => {
res.json({ status: 'ok' })
})
app.use('/api/notes', notesRouter)
app.use(notFound)
app.use(errorHandler)
export default appMiddleware is a function that runs on a request before (or instead of) your route. Express runs app.use lines from top to bottom, so the order is the plan:
helmet()adds security headers, such asX-Content-Type-Options: nosniff, to every response.cors(...)decides which other websites may read the answers (more in Step 5).express.json({ limit: '100kb' })reads JSON bodies intoreq.bodyand rejects bodies over 100 KB. A note has no business being 5 MB, and a limit stops one request from eating the server's memory.- The routes.
notFoundcatches any request no route answered, anderrorHandlercatches anything that went wrong. They must come last.
server.js stays exactly as in the structure lesson: it imports app and calls listen().
Step 2: The notes router
A router is a mini app that holds related routes. app.use('/api/notes', notesRouter) mounts it, so inside the router '/' means /api/notes and '/:id' means /api/notes/:id.
// server/src/routes/notes.js
import { Router } from 'express'
const router = Router()
// Temporary in-memory store. The next lesson replaces it with MongoDB.
const notes = [
{ id: '1', title: 'DBMS viva questions', body: 'Normal forms, keys, ACID', tags: ['college'], pinned: true },
{ id: '2', title: 'Sunday groceries', body: 'Atta 5 kg, toor dal, curd', tags: ['home'], pinned: false },
]
let nextId = 3
// GET /api/notes and GET /api/notes?tag=college
router.get('/', (req, res) => {
const { tag } = req.query
const result = typeof tag === 'string' ? notes.filter((n) => n.tags.includes(tag)) : notes
res.json({ notes: result })
})
// GET /api/notes/:id
router.get('/:id', (req, res) => {
const note = notes.find((n) => n.id === req.params.id)
if (!note) {
return res.status(404).json({ error: { code: 'NOT_FOUND', message: 'Note not found' } })
}
res.json({ note })
})
// POST /api/notes
router.post('/', (req, res) => {
const { title, body = '', tags = [], pinned = false } = req.body ?? {}
if (typeof title !== 'string' || title.trim() === '') {
return res
.status(400)
.json({ error: { code: 'VALIDATION_ERROR', message: 'Title is required' } })
}
const note = { id: String(nextId++), title: title.trim(), body, tags, pinned }
notes.push(note)
res.status(201).json({ note })
})
export default routerFour details are worth a second look:
req.queryholds the part after?. Never trust its type. A user can send?tag=a&tag=b, which gives an array, so the code filters only whentagis a string.req.params.idis always a string, because it comes from the URL. That is why the ids are strings too.req.body ?? {}: in Express 5,req.bodyisundefinedwhen no body parser handled the request, for example when a form sendstitle=xinstead of JSON. Destructuringundefinedwould crash, so we fall back to an empty object.return res.status(...): thereturnstops the function. Without it the code carries on and tries to send a second response, which fails with "Cannot set headers after they are sent".
This first check only covers the title. Checking body, tags and pinned properly is the job of CRUD Endpoints & Validation, and MongoDB's schema adds another layer next lesson. Until then, treat this store as a sketch.
Step 3: Try it with curl
Start the server (npm run dev inside server/, or from the root) and call each route. These are real responses from our run:
curl http://localhost:3000/api/notes
curl "http://localhost:3000/api/notes?tag=home"
curl -i http://localhost:3000/api/notes/9{"notes":[{"id":"1","title":"DBMS viva questions","body":"Normal forms, keys, ACID","tags":["college"],"pinned":true},{"id":"2","title":"Sunday groceries","body":"Atta 5 kg, toor dal, curd","tags":["home"],"pinned":false}]}
{"notes":[{"id":"2","title":"Sunday groceries","body":"Atta 5 kg, toor dal, curd","tags":["home"],"pinned":false}]}
HTTP/1.1 404 Not Found
Access-Control-Allow-Origin: http://localhost:5173
Vary: Origin
Content-Type: application/json; charset=utf-8
Content-Length: 57
{"error":{"code":"NOT_FOUND","message":"Note not found"}}-i shows the status line and headers (we removed Helmet's long list of security headers, the date and the ETag to save space). Now create a note, then try one without a title:
curl -X POST http://localhost:3000/api/notes -H "Content-Type: application/json" -d "{\"title\":\"Call Meera about the Pune trip\",\"tags\":[\"travel\"]}"
curl -X POST http://localhost:3000/api/notes -H "Content-Type: application/json" -d "{\"body\":\"no title\"}"{"note":{"id":"3","title":"Call Meera about the Pune trip","body":"","tags":["travel"],"pinned":false}}
{"error":{"code":"VALIDATION_ERROR","message":"Title is required"}}The first call returned status 201 and filled in the defaults (body empty, pinned false). Restart the server and note 3 is gone, because it lived only in memory. That is the problem the next lesson solves.
Step 4: JSON errors for everything
Two kinds of failure never reach your routes: a URL that matches no route, and a body that is not valid JSON. Express answers both with HTML by default. Our API promised JSON, so middleware/errors.js takes over:
// server/src/middleware/errors.js
// Runs when no route matched the request.
export function notFound(req, res) {
res.status(404).json({
error: { code: 'NOT_FOUND', message: `No route for ${req.method} ${req.originalUrl}` },
})
}
// Express knows this is an error handler because it has four parameters.
export function errorHandler(err, req, res, next) {
const status = err.status ?? 500
if (status >= 500) console.error(err)
res.status(status).json({
error: {
code: status >= 500 ? 'SERVER_ERROR' : 'BAD_REQUEST',
message: err.expose ? err.message : 'Something went wrong',
},
})
}Errors created by Express's own parts, such as express.json(), carry a status (400 for broken JSON, 413 for a body over the limit) and an expose flag that says the message is safe to show. Any other error becomes a plain 500 with a generic message, and the details go to the server log only. Never send err.stack to the client: it reveals file paths and library versions to attackers.
curl -X POST http://localhost:3000/api/notes -H "Content-Type: application/json" -d "{\"title\": \"oops\",}"
curl http://localhost:3000/api/nope{"error":{"code":"BAD_REQUEST","message":"Expected double-quoted property name in JSON at position 17 (line 1 column 18)"}}
{"error":{"code":"NOT_FOUND","message":"No route for GET /api/nope"}}The trailing comma made the JSON invalid. This is a first version of the handler; Error Handling & Middleware grows it into a full system with custom error classes.
Step 5: Let Vue call the API
The Vue dev server runs on http://localhost:5173 and the API on http://localhost:3000. Those are two different origins (an origin is scheme + host + port). Browsers block a page from reading responses from another origin unless that server says it is allowed. This rule is the same-origin policy, and CORS (Cross-Origin Resource Sharing) is how a server grants exceptions.
During development the simplest fix is to avoid the cross-origin call completely. Add a proxy to client/vite.config.js:
// client/vite.config.js (the server block is new)
export default defineConfig({
plugins: [vue(), vueDevTools()],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
server: {
proxy: {
'/api': 'http://localhost:3000',
},
},
})Now the browser asks Vite for /api/notes on its own origin, and Vite quietly forwards the request to Express, like a receptionist who passes your call to the right desk. That is why client.js uses the base URL /api. With both halves running we asked Vite (on port 5175 that day, because 5173 and 5174 were busy) for the health check and a note:
{"status":"ok"}
{"note":{"id":"2","title":"Sunday groceries","body":"Atta 5 kg, toor dal, curd","tags":["home"],"pinned":false}}In production the client and API may live on different origins, such as https://notenest.example and https://api.notenest.example. Then the cors middleware matters. Because config.clientOrigins is an allow-list (an array of exact origins), cors adds the Access-Control-Allow-Origin header only when the request's Origin is on the list:
curl -i -H "Origin: http://localhost:5173" http://localhost:3000/api/health
curl -i -H "Origin: https://evil.example" http://localhost:3000/api/healthAccess-Control-Allow-Origin: http://localhost:5173
That single line came from the first request. The second response had no CORS header at all, so a browser running a page from evil.example refuses to hand the data to its script. Note that CORS is enforced by browsers only; curl and other servers ignore it. It protects your users' browsers, not your API, so it never replaces login checks.
The page below plays the server's part with a copy of the POST route logic, so you can see the request Vue sends and the answer it gets for each input.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>POST /api/notes inspector</title>
<script src="https://cdn.jsdelivr.net/npm/vue@3.5.44/dist/vue.global.prod.js"></script>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; max-width: 34rem; }
label { display: block; margin-top: 8px; }
input { width: 100%; padding: 4px; }
pre { background: #f4f4f4; padding: 8px; white-space: pre-wrap; }
button { margin-top: 10px; }
</style>
</head>
<body>
<div id="app">
<h1>Create a note</h1>
<form @submit.prevent="send">
<label for="title">Title</label>
<input id="title" v-model="title">
<label for="tags">Tags (comma separated)</label>
<input id="tags" v-model="tags">
<button type="submit">Send POST /api/notes</button>
</form>
<h2>Request</h2>
<pre>{{ request }}</pre>
<h2>Response</h2>
<pre>{{ response }}</pre>
</div>
<script>
// Same logic as router.post('/') in server/src/routes/notes.js
let nextId = 3;
function fakeServer(bodyText) {
const { title, body = "", tags = [], pinned = false } = JSON.parse(bodyText) ?? {};
if (typeof title !== "string" || title.trim() === "") {
return { status: 400, json: { error: { code: "VALIDATION_ERROR", message: "Title is required" } } };
}
const note = { id: String(nextId++), title: title.trim(), body, tags, pinned };
return { status: 201, json: { note } };
}
Vue.createApp({
data() {
return { title: " Book Shatabdi tickets ", tags: "travel, home", request: "", response: "" };
},
methods: {
send() {
const payload = {
title: this.title,
tags: this.tags.split(",").map((t) => t.trim()).filter(Boolean)
};
const bodyText = JSON.stringify(payload);
this.request = "POST /api/notes\nContent-Type: application/json\n\n" + bodyText;
const res = fakeServer(bodyText);
this.response = "Status " + res.status + "\n\n" + JSON.stringify(res.json, null, 2);
}
}
}).mount("#app");
</script>
</body>
</html>Send it as it is, and the title comes back trimmed with status 201. Clear the title, or type only spaces, and you get the 400 error shape. The Vue code never has to guess: success always has note, failure always has error.message.
Common mistakes
- Putting
notFoundorerrorHandlerbefore the routes. Every request then gets a 404. Error middleware goes last. - Forgetting
returnafter an early response. The handler continues and Express throws "Cannot set headers after they are sent". - Testing CORS with curl and thinking it works. CORS headers only matter to browsers. Test from the real Vue page.
- Hard-coding
http://localhost:3000in Vue components. Use/apiwith the Vite proxy in development andVITE_API_URLin production. - Sending error details to the client. Stack traces and database messages belong in the server log, not in the JSON.
Interview questions
1. Why does a POST that creates something return 201 instead of 200?
201 Created tells the client that a new resource exists as a result of the request. Clients, tests and API tools can rely on it. The response body usually contains the new resource, including the id the server assigned.
2. What is the difference between the Vite proxy and CORS?
The proxy makes the browser talk only to the Vite dev server, which forwards /api requests to Express, so there is no cross-origin request at all. CORS is a set of response headers that let a browser accept a real cross-origin response. The proxy is for development; CORS settings matter when the client and API are on different origins in production.
3. How does Express recognise an error-handling middleware?
By its four parameters: (err, req, res, next). Express calls it only when an error is thrown or passed to next(err), and in Express 5 also when an async handler's promise rejects. It must be registered after the routes.
4. Why limit the size of JSON bodies?
Without a limit a client can send a huge body and make the server spend memory and CPU parsing it, which is a simple denial-of-service attack. express.json({ limit }) rejects oversized bodies early with a 413 status.
Key points
app.jsregisters Helmet, CORS,express.json({ limit }), the routers, thennotFoundanderrorHandler, in that order.- Routers group routes;
req.queryandreq.paramsare untrusted strings, andreq.bodymay beundefinedin Express 5. - Success responses wrap data (
{ notes },{ note }) and use 200 or 201; every error uses{ error: { code, message } }. - Unknown routes and broken JSON also get JSON errors, and 500 errors never expose details.
- In development, the Vite proxy forwards
/apito Express, so there is no cross-origin request. - In production,
corswith an explicit allow-list fromCLIENT_ORIGINcontrols which sites may read the API; never*with credentials.
Exercise
Add a GET /api/tags endpoint to NoteNest. It returns every tag used by any note, without repeats, sorted A to Z, together with how many notes use it: { "tags": [{ "name": "college", "count": 1 }, ...] }. Put the route in a new file routes/tags.js, mount it in app.js, and decide where in app.js the mount line must go. Then test it with curl.
Show solution
// server/src/routes/tags.js
import { Router } from 'express'
import { notes } from './notes.js'
const router = Router()
router.get('/', (req, res) => {
const counts = new Map()
for (const note of notes) {
for (const tag of note.tags) counts.set(tag, (counts.get(tag) ?? 0) + 1)
}
const tags = [...counts]
.map(([name, count]) => ({ name, count }))
.toSorted((a, b) => a.name.localeCompare(b.name))
res.json({ tags })
})
export default routerExport the array from routes/notes.js (export const notes = [...]), then add app.use('/api/tags', tagsRouter) next to the notes router, before notFound. If you put it after notFound, every call returns 404, because notFound answers first. With the two starting notes, curl http://localhost:3000/api/tags gives {"tags":[{"name":"college","count":1},{"name":"home","count":1}]}. In the next lesson the same endpoint becomes a short MongoDB query.
Quick Quiz
1. Where must app.use(errorHandler) go in app.js?
Express runs middleware in order; the error handler must come after the code that can fail.
2. A client sends title=x as a form body to the NoteNest API. What is req.body inside the route in Express 5?
No parser handled the form body, so the route falls back to {} and returns the 400 error.
3. Why does the NoteNest client use the base URL /api in development?
The browser talks to its own origin, and Vite passes the request on.
4. Which CORS setting is safe for an API that will use login cookies?
An allow-list names exactly which front ends may read responses with credentials.
Learn MEVN Stack with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
