Skip to content

Add sign-in to your API

Working knowledgeBuild alongNode + ExpressYou need: Build a REST API
What you’ll build: Your users API, with passwords stored as salted hashes, a session cookie after sign-in, and routes that refuse you until you have one. Seven steps, with a command after each to prove it works.POST /users with a passwordPOST /auth/loginGET /auth/mePOST /auth/logout401 for routes you can't see yet
Step 1 of 7

Start from your users API

Start from the finished project from Build a REST API from nothing: a users-api folder with Express installed, server.js, and the user routes in routes/users.js.

If you don't have it any more, run the commands below and copy in the two files.

WHY

Sign-in is a layer on top of an API you already have. Every later step changes these two files or adds a small one next to them.

This step runs:
terminal
$ mkdir users-api && cd users-api
$ npm init -y
$ npm install express
server.jsnew+14−0
Added: const express = require('express');
Added: const usersRouter = require('./routes/users');
Added: const app = express();
Added: app.use(express.json());
Added:
Added: app.get('/health', (req, res) => {
Added: res.json({ ok: true });
Added: });
Added:
Added: app.use('/users', usersRouter);
Added:
Added: app.listen(3000, () => {
Added: console.log('Listening on http://localhost:3000');
Added: });
routes/users.jsnew+24−0
Added: const express = require('express');
Added: const router = express.Router();
Added: const users = [];
Added:
Added: router.get('/', (req, res) => {
Added: res.json(users);
Added: });
Added:
Added: router.post('/', (req, res) => {
Added: if (!req.body?.name) {
Added: return res.status(400).json({ error: 'name is required' });
Added: }
Added: const user = { id: users.length + 1, name: req.body.name };
Added: users.push(user);
Added: res.status(201).json(user);
Added: });
Added:
Added: router.get('/:id', (req, res) => {
Added: const user = users.find((u) => u.id === Number(req.params.id));
Added: if (!user) return res.status(404).json({ error: 'Not found' });
Added: res.json(user);
Added: });
Added:
Added: module.exports = router;