Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 2 additions & 39 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,40 +1,3 @@
# Logs
logs
node_modules/
*.log
npm-debug.log*
*.bak


# Runtime data
pids
*.pid
*.seed

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# node-waf configuration
.lock-wscript

# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules
jspm_packages

# Optional npm cache directory
.npm

# Optional REPL history
.node_repl_history

.env
64 changes: 49 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,47 +1,81 @@
# express-locallibrary-tutorial

Tutorial "Local Library" website written in in Node/Express.
Tutorial "Local Library" website written in Node/Express.

---

This web application creates an online catalog for a small local library, where users can browse available books and manage their accounts.

![A UML diagram showing the relation of database entities in this example repository](https://raw.githubusercontent.com/mdn/express-locallibrary-tutorial/main/public/images/Library%20Website%20-%20Mongoose_Express.png)
![A UML diagram showing the relation of database entities in this example repository](https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/mongoose/library_website_-_mongoose_express.png)

For more information see the associated [MDN tutorial home page](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website).
For more information see the associated [MDN tutorial home page](https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Tutorial_local_library_website).

> **Note** The [auth branch](/../../tree/auth) in this repository implements an _unsupported_ and _undocumented_ version of the library with User Authentication and Authorization. This may be a useful starting point for some users.

## Try it without a database

If you just want to see the finished site, you don't need to set up MongoDB.
Install [Node.js](https://nodejs.org/en/download) 24 or later, clone this repo, and run these commands in its root:

```bash
npm install
npm run demo
```

Then open <http://localhost:3000/>.
The demo starts a temporary in-memory database and fills it with sample books, authors, genres and book copies.
Any changes you make are lost when you stop the server with <kbd>Ctrl</kbd>+<kbd>C</kbd>.
The first run downloads a MongoDB binary, so it may take a minute.

## Quick Start

To get this project up and running locally on your computer:
To set the project up for development, with a database that keeps your data:

1. Set up a [Node.js](https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/development_environment) development environment (Node.js 24 or later).
2. Make a MongoDB database available.
By default the app connects to a local MongoDB server at `mongodb://127.0.0.1:27017/local_library`.
You can:
- [Install MongoDB Community Edition](https://www.mongodb.com/docs/manual/administration/install-community/) locally.
- Run MongoDB in [Docker](https://docs.docker.com/get-started/get-docker/), keeping the data in a named volume:

1. Set up a [Node.js](https://wiki.developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/development_environment) development environment.
2. Once you have node setup install the project in the root of your clone of this repo:
```bash
docker run -d --name locallibrary-mongo -p 127.0.0.1:27017:27017 -v locallibrary-data:/data/db mongo:8
```

- Use a hosted database such as [MongoDB Atlas](https://www.mongodb.com/products/platform/atlas-database), and set the `MONGODB_URI` environment variable to its connection string.
3. Once you have node setup install the project in the root of your clone of this repo:

```bash
npm install
```

3. Run the tutorial server, using the appropriate command line shell for your environment:
4. Optionally, add some sample books, authors, genres and book copies to the database:

```bash
node populatedb.js "mongodb://127.0.0.1:27017/local_library"
```

5. Run the tutorial server, using the appropriate command line shell for your environment:

```bash
# Linux terminal
# Linux or macOS terminal
DEBUG=express-locallibrary-tutorial:* npm run devstart

# Windows Powershell
$ENV:DEBUG = "express-locallibrary-tutorial:*"; npm start
# Windows CMD
SET DEBUG=express-locallibrary-tutorial:* & npm run devstart

# Windows PowerShell
$ENV:DEBUG = "express-locallibrary-tutorial:*"; npm run devstart
```

4. Open a browser to <http://localhost:3000/> to open the library site.
The `devstart` script restarts the server when you change a JavaScript file.
Use `npm start` instead to run the server without watching for changes.

> [!NOTE]
> The library uses a default MongoDB database hosted on [MongoDB Atlas](https://www.mongodb.com/cloud/atlas).
> You should use a different database for your own code experiments.
6. Open a browser to <http://localhost:3000/> to open the library site.

## Contributing

The project is the result of carefully running through all the steps in the [tutorial on MDN](https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website).
The project is the result of carefully running through all the steps in the [tutorial on MDN](https://developer.mozilla.org/en-US/docs/Learn_web_development/Extensions/Server-side/Express_Nodejs/Tutorial_local_library_website).
Any changes to either MDN or this project must be synchronized.
Generally it is better to implement changes here before submitting them to MDN.

Expand Down
64 changes: 32 additions & 32 deletions app.js
Original file line number Diff line number Diff line change
@@ -1,66 +1,66 @@
const createError = require("http-errors");
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const logger = require("morgan");
const RateLimit = require("express-rate-limit");
import path from "node:path";
import createError from "http-errors";
import express from "express";
import logger from "morgan";
import compression from "compression";
import helmet from "helmet";
import RateLimit from "express-rate-limit";

const indexRouter = require("./routes/index");
const usersRouter = require("./routes/users");
const catalogRouter = require("./routes/catalog"); // Import routes for "catalog" area of site

const compression = require("compression");
const helmet = require("helmet");
import indexRouter from "./routes/index.js";
import usersRouter from "./routes/users.js";
import catalogRouter from "./routes/catalog.js"; // Import routes for "catalog" area of site

const app = express();

// Set up rate limiter: maximum of twenty requests per minute
const limiter = RateLimit({
windowMs: 1 * 60 * 1000, // 10 seconds
max: 60,
windowMs: 1 * 60 * 1000, // 1 minute
max: 20,
});
// Apply rate limiter to all requests
app.use(limiter);

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

// Add helmet to the middleware chain.
// Set CSP headers to allow our Bootstrap scripts to be served
app.use(
helmet.contentSecurityPolicy({
directives: {
"script-src": ["'self'", "cdn.jsdelivr.net"],
},
})
}),
);

// view engine setup
app.set("views", path.join(import.meta.dirname, "views"));
app.set("view engine", "pug");

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(compression()); // Compress all routes

app.use(express.static(path.join(__dirname, "public")));
app.use(express.static(path.join(import.meta.dirname, "public")));

app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/catalog", catalogRouter); // Add catalog routes to middleware chain.

// catch 404 and forward to error handler
app.use(function (req, res, next) {
app.use((req, res, next) => {
next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
app.use((err, req, res, next) => {
if (res.headersSent) {
next(err);
return;
}

res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};

// render the error page
res.status(err.status || 500);
res.status(err.status ?? 500);
res.render("error");
});

module.exports = app;
export default app;
115 changes: 0 additions & 115 deletions bin/www

This file was deleted.

Loading