New to Rust? Grab our free Rust for Beginners eBook Get it free →
How to Build a Todo App with Express and EJS

Adding a task through a browser form only helps if the page then shows the updated list. Express handles the form request, while EJS turns task data into HTML for the browser.
I’ll show how to set up the Node.js project and connect form submissions to the rendered task list.
TL;DR
Build this todo app with Express routes for showing and changing tasks, then let EJS render the in-memory array as HTML. The array suits a small exercise, but its contents return to the seed data when the Node.js process stops.
- Install Express and EJS in a new Node.js project.
- Parse ordinary HTML form submissions before the routes.
- Render escaped task text and redirect after each successful change.
What Is an Express and EJS Todo App?
An Express-and-EJS todo app accepts task submissions through a browser form and returns a server-rendered list. It keeps the example focused on a form-to-page interaction because the route and template are simpler to follow without client-side code.
| Request stage | Value passed onward |
|---|---|
| HTML form | A field named todoTask contains the submitted text. |
| Express middleware | The URL-encoded field becomes a property on req.body. |
| Route handler | A task object is added to the todo array. |
| EJS view | Each task object becomes a row in the returned HTML. |
Express runs URL-encoded middleware before matching the handler, which reads req.body.todoTask.
How to Build the Todo App Step by Step
Keep the route code in one file while the example remains small.
Step 1: Create the Node.js Project
Start with Node.js and npm. Express 5 requires Node.js 18 or later. Create an empty directory for the project.
node --version npm --version npm init -y npm install express ejs
npm init -y creates package.json without an interactive questionnaire. npm install express ejs installs project-local packages and records their resolved versions in package-lock.json.
Run the setup commands from the project root so npm updates the manifest and lockfile in the expected folder. Node’s built-in fetch avoids adding a separate HTTP test-client dependency.
Create app.js and a views/index.ejs file in the project directory. Express defaults to a folder named views, and app.set(‘view engine’, ‘ejs’) selects the template engine.
The files use CommonJS syntax, which is why the app imports Express with require() and exports createApp() with module.exports. Keep this module format consistent if adding another JavaScript file to the project.
Step 2: Add the Routes and Task Array
The const binding keeps the same array reference while push() and splice() change its entries. nextId uses let because each successful add advances the number assigned to the next task.
const express = require('express');
function createApp() {
const app = express();
const todos = [{ id: 1, task: 'Review pull request' }];
let nextId = 2;
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: false }));
app.get('/', (req, res) => {
res.render('index', { todos, error: '' });
});
app.post('/todos', (req, res) => {
const task = typeof req.body?.todoTask === 'string'
? req.body.todoTask.trim()
: '';
if (!task) {
return res.status(400).render('index', {
todos,
error: 'Enter a task before adding it.'
});
}
todos.push({ id: nextId, task });
nextId += 1;
return res.redirect(303, '/');
});
app.post('/todos/:id/delete', (req, res) => {
const id = Number(req.params.id);
const index = todos.findIndex((todo) => todo.id === id);
if (!Number.isInteger(id) || index === -1) {
return res.sendStatus(404);
}
todos.splice(index, 1);
return res.redirect(303, '/');
});
return app;
}
if (require.main === module) {
const port = Number(process.env.PORT || 3000);
createApp().listen(port, () => {
console.log(`Todo app listening on http://localhost:${port}`);
});
}
module.exports = { createApp };
The require.main guard starts the listener only when app.js is run directly. Exporting createApp() lets the test import the configured routes without opening the default port first.
Set extended to false because the form sends one flat name/value field.
The handler checks that the incoming value is a string before trimming it. That guard also handles a missing body, which can occur when the request content type does not match the URL-encoded parser.
The 303 response uses the Post/Redirect/Get flow: the form submission changes state, and a following GET renders the page. This separates the browser’s page refresh from the original form submission.
Express exposes :id as a string, so convert it with Number before comparing it to numeric IDs. findIndex() returns -1 when no object matches, and the guard responds 404 before the array changes. On a match, splice(index, 1) removes precisely one item.
The counter stays separate from array positions because deleting one row shifts later indexes.
Step 3: Render the List in EJS
Place the add form before the task list and render one list item for each object.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Todo List</title>
</head>
<body>
<main>
<h1>Todo List</h1>
<form action="/todos" method="post">
<label for="todoTask">New task</label>
<input id="todoTask" name="todoTask" type="text" required>
<button type="submit">Add task</button>
</form>
<% if (error) { %>
<p role="alert"><%= error %></p>
<% } %>
<ul>
<% todos.forEach((todo) => { %>
<li>
<span><%= todo.task %></span>
<form action="/todos/<%= todo.id %>/delete" method="post">
<button type="submit" aria-label="Delete <%= todo.task %>">Delete</button>
</form>
</li>
<% }); %>
</ul>
</main>
</body>
</html>
The forEach loop emits one list item per task object. The label’s for value matches the input’s id, which connects the visible prompt to the text field.
Each task row includes its own POST form, and its action contains the task ID. The aria-label uses the task text so assistive technology can distinguish the Delete buttons.
Use the EJS output tag <%= value %> for task text so user input is escaped as HTML text. Avoid the raw-output tag for task names because it can insert user markup into the page. The control tag <% statements %> runs the loop without writing its JavaScript into the response.
The validation message appears only when the route passes an error value, and role=”alert” exposes it to assistive technology. A completion toggle or editor would need another form and handler, so neither belongs in this build.
Step 4: Run and Verify the App
Start the server from the project directory, then open the local URL printed in its message. The port can be supplied through PORT when the default port is already in use.
PORT=3101 node app.js
Open http://localhost:3101/ in a browser. The list should show Review pull request with an add form.
Submit a task and use that row’s Delete button. The browser shows the current list after each action.
I ran node todo_app_demo.js against these routes. The named source file checks response codes and the rendered page, then closes its temporary server.
const assert = require('node:assert/strict');
const { createApp } = require('./app');
async function main() {
const server = createApp().listen(0, '127.0.0.1');
try {
await new Promise((resolve) => server.once('listening', resolve));
const address = server.address();
const base = `http://127.0.0.1:${address.port}`;
const initial = await fetch(base);
const initialHtml = await initial.text();
assert.equal(initial.status, 200);
assert.match(initialHtml, /Review pull request/);
console.log('GET / -> 200; rendered "Review pull request"');
const add = await fetch(`${base}/todos`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ todoTask: 'Ship fix' }),
redirect: 'manual'
});
assert.equal(add.status, 303);
assert.equal(add.headers.get('location'), '/');
console.log('POST /todos with "Ship fix" -> 303; Location: /');
const afterAdd = await fetch(base);
const afterAddHtml = await afterAdd.text();
assert.match(afterAddHtml, /Ship fix/);
console.log('GET / -> 200; rendered "Ship fix"');
const unsafeText = '<script>alert(1)</script>';
const unsafeAdd = await fetch(`${base}/todos`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ todoTask: unsafeText }),
redirect: 'manual'
});
assert.equal(unsafeAdd.status, 303);
const unsafePage = await fetch(base);
const unsafeHtml = await unsafePage.text();
assert.match(unsafeHtml, /<script>alert\(1\)<\/script>/);
assert.doesNotMatch(unsafeHtml, /<script>/);
console.log('POST /todos with markup -> 303; EJS output escaped');
const blank = await fetch(`${base}/todos`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ todoTask: ' ' }),
redirect: 'manual'
});
const blankHtml = await blank.text();
assert.equal(blank.status, 400);
assert.match(blankHtml, /Enter a task before adding it/);
console.log('POST /todos with blank task -> 400; validation message rendered');
const unparsed = await fetch(`${base}/todos`, {
method: 'POST',
body: 'todoTask=Ship+without+form+encoding',
redirect: 'manual'
});
const unparsedHtml = await unparsed.text();
assert.equal(unparsed.status, 400);
assert.match(unparsedHtml, /Enter a task before adding it/);
console.log('POST /todos without form encoding -> 400; no server error');
const remove = await fetch(`${base}/todos/1/delete`, {
method: 'POST',
redirect: 'manual'
});
assert.equal(remove.status, 303);
assert.equal(remove.headers.get('location'), '/');
console.log('POST /todos/1/delete -> 303; Location: /');
const missingDelete = await fetch(`${base}/todos/999/delete`, {
method: 'POST',
redirect: 'manual'
});
assert.equal(missingDelete.status, 404);
console.log('POST /todos/999/delete -> 404; unknown ID preserved');
const afterDelete = await fetch(base);
const afterDeleteHtml = await afterDelete.text();
assert.equal(afterDelete.status, 200);
assert.doesNotMatch(afterDeleteHtml, /Review pull request/);
assert.match(afterDeleteHtml, /Ship fix/);
console.log('GET / -> 200; deleted task absent, remaining task present');
const next = await fetch(`${base}/todos`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({ todoTask: 'Review docs' }),
redirect: 'manual'
});
assert.equal(next.status, 303);
const afterNext = await fetch(base);
const afterNextHtml = await afterNext.text();
assert.match(afterNextHtml, /\/todos\/3\/delete/);
console.log('POST /todos with "Review docs" -> 303; next ID remains unique');
console.log('All todo app checks passed.');
} finally {
await new Promise((resolve, reject) => server.close((error) => error ? reject(error) : resolve()));
}
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
Run the test from the project root with Node.js. The script binds the app to an available local port, uses built-in fetch and assert, and closes the server in finally.
Each POST sets redirect: ‘manual’ so the test can inspect the 303 and Location before requesting the next page.
node todo_app_demo.js
GET / -> 200; rendered "Review pull request" POST /todos with "Ship fix" -> 303; Location: / GET / -> 200; rendered "Ship fix" POST /todos with markup -> 303; EJS output escaped POST /todos with blank task -> 400; validation message rendered POST /todos without form encoding -> 400; no server error POST /todos/1/delete -> 303; Location: / POST /todos/999/delete -> 404; unknown ID preserved GET / -> 200; deleted task absent, remaining task present POST /todos with "Review docs" -> 303; next ID remains unique All todo app checks passed.
The 200 lines confirm rendered pages, and 303 plus Location shows successful writes return redirects. The final success line appears only after all assertions complete.
An unencoded request verifies the absent-body case. The delete checks also cover both an existing ID and an unknown one.

What Can Break in This In-Memory Todo App?
This example accepts ordinary text forms and uses explicit route responses for invalid input and unknown task IDs. Keep this parser narrow because the app only accepts a flat task name. When adding a new form field, update the HTML name, route validation, and test together so a mismatch is caught before someone depends on the new field.
| Symptom | Cause to check | Fix |
|---|---|---|
| req.body.todoTask is missing | The form name differs from the route property, or URL-encoded middleware is absent or registered after the route. | Match the name to todoTask and register express.urlencoded() before the routes. |
| Form values still do not parse | The client sent multipart/form-data rather than a standard URL-encoded form. | This tutorial accepts ordinary browser forms. Add multipart parsing only if the app later needs uploads. |
| A blank row appears | The server accepts spaces as task text. | Trim the value and return a validation response when it is empty. |
| The wrong task disappears | The delete form submits stale text or a reused array index. | Submit a stable task ID and locate one matching array index before removal. |
| Tasks vanish after a restart | The list exists only in the process memory. | Use a database or another durable store when data must persist. |
When the server reports that a port is already in use, choose another unprivileged port, such as PORT=3101 node app.js, and confirm that the browser uses that port.
A form that appears to submit without changing the page may use an action, method, or input name that does not match the POST handler. Inspect the request in the browser’s developer tools.
When data needs to survive a restart, load task records for GET /, insert records on POST /todos, and delete by a validated ID, with database-assigned identifiers that remain stable across process starts.
Pass only the data the view needs, such as todos and error, rather than the full request object so the template’s inputs remain clear when a page renders unexpected values.
After making a route change, repeat the relevant checks: add an ordinary task, submit a blank value, try an unknown delete ID, and verify the resulting page, since those cases exercise distinct branches.
After the final task is deleted, the current template leaves the list element empty. Add a distinct empty-state message only if readers need guidance about that valid state.
The required attribute gives browser users a prompt but cannot constrain requests from custom clients.
Authenticated apps that use browser cookies need cross-site request forgery protection on state-changing forms.
The test also sends a request without form encoding and confirms the route handles its missing field without crashing, which protects the server from an unexpected body shape.
A completion toggle is a separate feature from deleting a task. It needs a boolean field on the task object, a POST route that changes that field for one validated ID, and a control in the row form. Render the completed state with text as well as styling so the change remains understandable without color.
The current sample intentionally omits that route, which keeps add and delete behavior distinct while the basic request cycle is being learned. Before adding it, decide whether completed tasks stay in the same list or move to another view, since that choice changes what the GET route should render.
What to Do Next
With the add and delete routes working, the next change depends on what the app must retain. Check the two limits below before extending this in-memory version.
| Need | Next step |
|---|---|
| Tasks must survive a restart | Move the task array to a database and test reads, inserts, and deletes against stored records. |
| Several users share the app | Associate each task with its owner and check ownership on reads and deletes. |
| Users need a completion state | Add a completed boolean and a route that updates one validated task ID. |
I would add persistence before a completion toggle when tasks must outlast the process, because a new field in the same array still disappears on restart.
Conclusion: Keep the Form-to-View Path Clear
Persistence and privacy are separate requirements. A multi-user app needs ownership checks on reads and deletes so one user’s records cannot be changed by another.
For an overview of the runtime, continue with the CodeForGeek Node runtime guide. Its guide to Express routes and responses shows the request-handler boundary. The Express template-engine guide explains view rendering.
The EJS documentation describes escaped output and template tags. For a later project, decide whether tasks need a longer lifetime than one server process.
FAQ
These answers clarify the two limits a short in-memory tutorial can leave open.
Do tasks remain after the Node.js server restarts?
No. The app stores tasks in an in-memory array, so a restart creates the seed list again. Use persistent storage when tasks must survive a restart.
Why does Express receive an empty task value?
Check that the form input is named todoTask and that express.urlencoded() runs before the POST route. The middleware in this example handles ordinary URL-encoded form submissions, not multipart uploads.




