Skip to content

πŸŽ“ Production ready express setup - CMDA Backend

Notifications You must be signed in to change notification settings

Murderlon/be-assessment-2

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

54 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

be-assessment-2

Production ready express setup.

Content

πŸ— Architecture

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
└─ ...

πŸ” Security

Simple, unobtrusive authentication

Secure Express apps by setting various HTTP headers.

πŸ” Sessions

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.

⬆️ Uploads

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))
})

β€πŸ’» Install

  1. Get a MongoDB database, either locally or online.
  1. Get this repository.
$ git clone https://github.com/Murderlon/be-assessment-2.git
  1. Install dependencies.
$ yarn

or

$ npm install
  1. Create your .env file (and fill in the empty variables).
$ echo 'DB_URL=
  SESSION_SECRET=' > .env
  1. Run it.
yarn start

or

npm start

That's it!

βš–οΈ Licence

MIT Β© Merlijn Vos.

About

πŸŽ“ Production ready express setup - CMDA Backend

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published