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.