Production ready
express
setup.
Architecture is done as modular as possible, server.js
only serves as a high-level overview as it passes further middleware setup to lib/
and requests to distinguished routers in routes/
.
be-assessment-2/
├─ lib/
├─ models/
├─ node_modules/
├─ routes/
├─ static/
│ └─ img/
│ └─ ...
├─ view/
│ └─ partials/
│ └─ ...
├─ .env
├─ package.json
├─ README.md
├─ server.js
└─ ...
Simple, unobtrusive authentication
Secure Express apps by setting various HTTP headers.
User can stay logged in through express-session
. Additionally, when the server restarts the sessions stay in place because they are saved in MongoDB
with connect-mongo
, as can be seen by the store
property below.
// ...
.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection })
})
)
// ...
The process.env.SESSION_SECRET
is a 64 character crypto string.
File uploads are done with multer
with custom settings to generate unique file names with shortid
. How unique are pseudo-random generators you may ask? According to this answer on Stackoverflow we're pretty safe:
While shortid's are not guaranteed to be unique, the likelihood of a collision is extremely small. Unless you generate billions of entries per year, you could safely assume that a collision will never happen.
Custom settings for multer
:
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, 'static/img'),
filename: (req, { originalname }, cb) =>
cb(null, shortid.generate() + path.extname(originalname))
})
- Get a MongoDB database, either locally or online.
- Get this repository.
$ git clone https://github.com/Murderlon/be-assessment-2.git
- Install dependencies.
$ yarn
or
$ npm install
- Create your
.env
file (and fill in the empty variables).
$ echo 'DB_URL=
SESSION_SECRET=' > .env
- Run it.
yarn start
or
npm start
That's it!
MIT © Merlijn Vos.