hoangvvo / nextjs-mongodb-app

A Next.js and MongoDB web application, designed with simplicity for learning and real-world applicability in mind.
https://nextjs-mongodb.now.sh/
MIT License
1.53k stars 286 forks source link

How to make it more secure? #106

Open sakhmedbayev opened 3 years ago

sakhmedbayev commented 3 years ago

Thank you for the repo and tutorials!

The readme tells that

Due to its simplicity, aspects such as security must be reconsidered before being used in production.

What would be your recommendations to improve the security of the current approach?

ItaiAxelrad commented 3 years ago

Similar to an express app, adding middlewares can help improve security. I think helmet is a great start, along with a rate limiter like express-rate-limit and maybe cors.

As an example, create a new file for your desired middleware:

// @/middlewares/helmet.js
import helmet from 'helmet';

helmet.contentSecurityPolicy({
  directives: {
    ...helmet.contentSecurityPolicy.getDefaultDirectives(),
    'script-src': ['self', process.env.WEB_URI],
  },
  reportOnly: process.env.NODE_ENV === 'development',
});

export default helmet;

Then add the middleware into the chain of use methods of next-connect:

// middlewares/all.js
const middleWares = nc().use(helmet).use(cors)... // rest of middleswares

Hope that helps!

ItaiAxelrad commented 3 years ago

Forgot to add that having some sort of schema validation can also help with security. Mongoose is a popular Object Data Modeling (ODM) package though MongoDB now offers its own schema validation.