A MERN boilerplate repository with RBAC feature, following all production best practices.

Overview

Welcome to the RBAC MERN Boilerplate project

A MERN boilerplate repository with RBAC feature, following all production best practices.

In this repository I will keep adding the production best practices we should follow in a MERN (MongoDB, Express.js, React.js, and Node.js) project.

Product List Page

Technology stack

As the name suggests, this repository is built on top of Express.js and React.js, however in the implementation detail, we will find other supporting technologies as well.

Client side

  • React - A JavaScript library for building user interfaces
  • MongoDB - The application data platform
  • Ant Design - A design system for enterprise-level products. Create an efficient and enjoyable work experience
  • Testing Library - React Testing Library
  • Axios - Promise based HTTP client for the browser and node.js
  • Styled Components - Visual primitives for the component age

Server side

Details frameworks and packages can be found in the package.json files in server and client directory.

Run the application

This project can be run basically in two ways. One is using docker, other way is to run manually via vscode.

Docker

Prerequisites
  • Docker : To run docker-compose command

Go to the root of the repository and execute npm start. This will spin up the server and client containers along with the MongoDB instance inside of Docker environment.

cd project-root
npm start

Visual Studio Code

Prerequisites
  • Node.js : To run npm packages
  • Docker : To run MongoDB database
Steps
  • To run via vscode, we should run the server and client side projects separately, and also make sure mongodb is up and running.
  • Create a .env file inside of the server directory. Add the below entries
    DB_HOST=localhost
    DB_PORT=27017
    DB_NAME=appdb
    

Server commands

cd server
npm i
npm run db:up
npm start

Client commands

cd client
npm i
npm start

Test client app

To view the client, open your browser and visit http://localhost:3000 url. For the demo purpose, the authentication and authorization is not controlled from database entry and purely handled in client side.

The system has a role-based-access-control system which is controlled by permissions assigned to the role. The system supports different types of permissions in the client side. Depending on the role, side menu, the actual page (route) can be visible or not. More of that, any individual control/components can also be enabled / disabled depending on the role as well.

Superman in the role of SuperAdmin

To login as SuperAdmin we input [email protected] as email and put anything as the password. Upon login, the user should see superadmin's menus (Role, User, Resource, Permission) at the left side.

Pikachu in the role of User

To login as User, we input any valid email and anything as password. Upon login, the user should see menus (Product, Customer) at the left side.

Change the permissions

Ideally we should handle the permissions in server side and store in database (mongodb), but for this demo, we will modify the data in the clint side and mimic the server side behavior. To change User's permission, go to client/src/data/user-pikachu.json and add/update entry in the permissions array. A sample permission entry is like

{
  "_id": "5c8d03505653de3f85aa1ff",
  "resourceName": "customers-add",
  "resourceType": "route",
  "isAllowed": true,
  "isDisabled": false
}

To disable a button, we can set isDisabled = true like below

{
  "_id": "5c8d0c505653de3985aa0f1",
  "resourceName": "product-edit-button",
  "resourceType": "button",
  "isAllowed": true,
  "isDisabled": true
}

Centralized log to Sentry.io

We can also send the logs to sentry.io. To use this feature, we need to add the dsn entry into client/src/env.config.js. Setup snippet is like below in index.js file

Sentry.init({
  dsn: Config.dsn,
  integrations: [new Integrations.BrowserTracing()],
  tracesSampleRate: 1.0,
});

Test server API

To view the api, open your browser and visit http://localhost:5000/api-docs Ideally we should add all of the API endpoints into the swagger, but for the demo purpose, we only added Products API endpoint.
To test the APIs, we can reuse the postman collection. Open docs/rbac-mern-boilerplate.postman_collection.json into Postman and you should see the endpoints with appropriate payloads.

Scripts

Project Command Task
root npm run build Builds the containers
root npm run start Start the projects and database in docker containers
root docker exec -it appserver /bin/sh then npm run db:seed Executes seed products inside container
server npm i Install server side dependencies
server npm run db:up Start the database in a docker container
server npm run db:seed Seed products data into database
server npm run test Execute tests using jest
client npm i Install client side dependencies
client npm run start Start the react app
client npm run build Build the react app in production mode
client npm run test Execute tests using Testing Library

Types of testing

In this repository, we have included both unit testing and integration testing. For now, the code coverage is very low, but we are working on it to make it more than 90% somewhere in the future

Client side

  • We incorporated only unit tests in client side, and mock all the externals dependencies like localStorage and axios.

To run the tests, we can run npm run test command.

Server side

  • Integration testing: We have integrated the Jest as the testing library, and we have added supertest and mongodb-memory-server packages to make the integration testing easier.
  • Unit testing: We have used Jest to test the service layers and mock the external dependencies like MongoDB.

To run the tests, we can run npm run test command.

License

This project is MIT licensed.

Comments
  • Add description, manufacturingDate, expiryDate, & size fields in products.json file

    Add description, manufacturingDate, expiryDate, & size fields in products.json file

    The error was occurring as description, manufacturingDate, expiryDate, & size are defined as required in the product schema but those fields were missing in the products.json file. I have added those fields to the products.json file and the seed is now working.

    opened by minhajul-karim 5
  • Fix Radix Param, nested ternary, expected '===', console.log

    Fix Radix Param, nested ternary, expected '===', console.log

    #34 Issue

    • Fixed Radix parameters error
    • Changed nested ternary to regular expression
    • changed == to === for type check
    • Ignored console.log (it might be needed)
    opened by abidr 3
  • Refactor from httpServices to Model pattern

    Refactor from httpServices to Model pattern

    • Added command in Dockerfile for mac m1
    • Changed dockerfile of front-end to working on hot reload
    • Moved all high level function to models and only http verbs on the httpService. httpService.js is the layer, where developer can replace the axios with any other tools to communicate with API.
    opened by fereloper 3
  • IS_MONGODB_CLOUD_URL turn into boolen

    IS_MONGODB_CLOUD_URL turn into boolen

    In connectWithDb function when we collect IS_MONGODB_CLOUD_URL from env it gives us a value as a string, So if we check is it false or true it always returns true. So I turn it into a boolean using the Boolean function.

    opened by tusheer 2
  • DB seed for users and role

    DB seed for users and role

    Dear Foyzul Karim please create seed for users and roles Thanks.

    Your name in Arabic Foyzul : فيض الله means : God's gift or God's Excess Giving or Generous of God Karim : كريم means :Generous

    opened by mrs01dev 2
  • `ValidationError: Product validation failed` error when running `npm run db:seed`

    `ValidationError: Product validation failed` error when running `npm run db:seed`

    When I run npm run db:seed to seed the database, it is giving me below error.

    image

    You can get hits how to solve this in this video: https://youtu.be/UhXjemzbNSs?t=1192

    Full terminal output:

    > [email protected] db:seed /Users/foyzul/Documents/foyzul/github/rbac-mern-boilerplate/server
    > node ./setup/seed-products.js
    
    Seed starting
    mongodb://localhost:27017/appdb
    Seed finished
    (node:32458) DeprecationWarning: collection.ensureIndex is deprecated. Use createIndexes instead.
    (Use `node --trace-deprecation ...` to show where the warning was created)
    Database connection established
    /Users/foyzul/Documents/foyzul/github/rbac-mern-boilerplate/server/node_modules/mongoose/lib/document.js:2760
        this.$__.validationError = new ValidationError(this);
                                   ^
    
    ValidationError: Product validation failed: size: Path `size` is required., expiryDate: Path `expiryDate` is required., manufacturingDate: Path `manufacturingDate` is required., description: Path `description` is required.
        at model.Document.invalidate (/Users/foyzul/Documents/foyzul/github/rbac-mern-boilerplate/server/node_modules/mongoose/lib/document.js:2760:32)
        at /Users/foyzul/Documents/foyzul/github/rbac-mern-boilerplate/server/node_modules/mongoose/lib/document.js:2552:17
        at /Users/foyzul/Documents/foyzul/github/rbac-mern-boilerplate/server/node_modules/mongoose/lib/schematype.js:1273:9
        at processTicksAndRejections (node:internal/process/task_queues:78:11)
        at runNextTicks (node:internal/process/task_queues:65:3)
        at processImmediate (node:internal/timers:437:9) {
      errors: {
        size: ValidatorError: Path `size` is required.
            at validate (/Users/foyzul/Documents/foyzul/github/rbac-mern-boilerplate/server/node_modules/mongoose/lib/schematype.js:1270:13)
            at /Users/foyzul/Documents/foyzul/github/rbac-mern-boilerplate/server/node_modules/mongoose/lib/schematype.js:1253:7
            at Array.forEach (<anonymous>)
            at SchemaNumber.SchemaType.doValidate (/Users/foyzul/Documents/foyzul/github/rbac-mern-boilerplate/server/node_modules/mongoose/lib/schematype.js:1198:14)
            at /Users/foyzul/Documents/foyzul/github/rbac-mern-boilerplate/server/node_modules/mongoose/lib/document.js:2545:18
            at processTicksAndRejections (node:internal/process/task_queues:78:11)
            at runNextTicks (node:internal/process/task_queues:65:3)
            at processImmediate (node:internal/timers:437:9) {
          properties: {
            validator: [Function (anonymous)],
            message: 'Path `size` is required.',
            type: 'required',
            path: 'size',
            value: undefined
          },
          kind: 'required',
          path: 'size',
          value: undefined,
          reason: undefined,
          [Symbol(mongoose:validatorError)]: true
        },
        expiryDate: ValidatorError: Path `expiryDate` is required.
            at validate (/Users/foyzul/Documents/foyzul/github/rbac-mern-boilerplate/server/node_modules/mongoose/lib/schematype.js:1270:13)
            at /Users/foyzul/Documents/foyzul/github/rbac-mern-boilerplate/server/node_modules/mongoose/lib/schematype.js:1253:7
            at Array.forEach (<anonymous>)
            at SchemaDate.SchemaType.doValidate (/Users/foyzul/Documents/foyzul/github/rbac-mern-boilerplate/server/node_modules/mongoose/lib/schematype.js:1198:14)
            at /Users/foyzul/Documents/foyzul/github/rbac-mern-boilerplate/server/node_modules/mongoose/lib/document.js:2545:18
            at processTicksAndRejections (node:internal/process/task_queues:78:11)
            at runNextTicks (node:internal/process/task_queues:65:3)
            at processImmediate (node:internal/timers:437:9) {
          properties: {
            validator: [Function (anonymous)],
            message: 'Path `expiryDate` is required.',
            type: 'required',
            path: 'expiryDate',
            value: undefined
          },
          kind: 'required',
          path: 'expiryDate',
          value: undefined,
          reason: undefined,
          [Symbol(mongoose:validatorError)]: true
        },
        manufacturingDate: ValidatorError: Path `manufacturingDate` is required.
            at validate (/Users/foyzul/Documents/foyzul/github/rbac-mern-boilerplate/server/node_modules/mongoose/lib/schematype.js:1270:13)
            at /Users/foyzul/Documents/foyzul/github/rbac-mern-boilerplate/server/node_modules/mongoose/lib/schematype.js:1253:7
            at Array.forEach (<anonymous>)
            at SchemaDate.SchemaType.doValidate (/Users/foyzul/Documents/foyzul/github/rbac-mern-boilerplate/server/node_modules/mongoose/lib/schematype.js:1198:14)
            at /Users/foyzul/Documents/foyzul/github/rbac-mern-boilerplate/server/node_modules/mongoose/lib/document.js:2545:18
            at processTicksAndRejections (node:internal/process/task_queues:78:11)
            at runNextTicks (node:internal/process/task_queues:65:3)
            at processImmediate (node:internal/timers:437:9) {
          properties: {
            validator: [Function (anonymous)],
            message: 'Path `manufacturingDate` is required.',
            type: 'required',
            path: 'manufacturingDate',
            value: undefined
          },
          kind: 'required',
          path: 'manufacturingDate',
          value: undefined,
          reason: undefined,
          [Symbol(mongoose:validatorError)]: true
        },
        description: ValidatorError: Path `description` is required.
            at validate (/Users/foyzul/Documents/foyzul/github/rbac-mern-boilerplate/server/node_modules/mongoose/lib/schematype.js:1270:13)
            at /Users/foyzul/Documents/foyzul/github/rbac-mern-boilerplate/server/node_modules/mongoose/lib/schematype.js:1253:7
            at Array.forEach (<anonymous>)
            at SchemaString.SchemaType.doValidate (/Users/foyzul/Documents/foyzul/github/rbac-mern-boilerplate/server/node_modules/mongoose/lib/schematype.js:1198:14)
            at /Users/foyzul/Documents/foyzul/github/rbac-mern-boilerplate/server/node_modules/mongoose/lib/document.js:2545:18
            at processTicksAndRejections (node:internal/process/task_queues:78:11)
            at runNextTicks (node:internal/process/task_queues:65:3)
            at processImmediate (node:internal/timers:437:9) {
          properties: {
            validator: [Function (anonymous)],
            message: 'Path `description` is required.',
            type: 'required',
            path: 'description',
            value: undefined
          },
          kind: 'required',
          path: 'description',
          value: undefined,
          reason: undefined,
          [Symbol(mongoose:validatorError)]: true
        }
      },
      _message: 'Product validation failed'
    }
    npm ERR! code ELIFECYCLE
    npm ERR! errno 1
    npm ERR! [email protected] db:seed: `node ./setup/seed-products.js`
    npm ERR! Exit status 1
    npm ERR! 
    npm ERR! Failed at the [email protected] db:seed script.
    npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
    
    npm ERR! A complete log of this run can be found in:
    npm ERR!     /Users/foyzul/.npm/_logs/2021-09-21T03_52_39_643Z-debug.log
    
    bug 
    opened by foyzulkarim 2
  • Permission seed data prepared

    Permission seed data prepared

    Use case

    • Login as superadmin --> Can access users, roles, resources, permissions page
    • Login as admin --> Can access only users page
    • Login as user --> Can access only products page
    opened by foyzulkarim 1
  • colorful logging with winston logger

    colorful logging with winston logger

    Created a simple logger with winston. It will be logging to console like this...

    loggerScreenShot

    It won't break any other codes. Now we can change all console.log to logger.info or logger.warn or logger.error .

    opened by farhancdr 1
  • Implemented authorization handler in expressjs middleware

    Implemented authorization handler in expressjs middleware

    Implemented authorization handler in expressjs middleware. Also added some permission entries as required. Rest of the entries will be taken care of later.

    opened by foyzulkarim 0
  • Pls upgrade client boilerplate code to react-router v6

    Pls upgrade client boilerplate code to react-router v6

    This boilerplate is the most comprehensive and production quality boilerplates on Github and so has set high expectations for everyone. I have recommended this boilerplate to many guys.

    Few suggestions:

    1. Pls upgrade to react-router v6. This will simplify boilerplate by some factor.
    2. Moment.js has been deprecated in favor of new Intl API. You can also use React Intl npm package.
    3. More descriptive and explainatory comments in server side code.
    opened by kedarpethe37 0
  • Customer module simple CRUD

    Customer module simple CRUD

    Task description and acceptance criteria

    Complete the CRUD operation for Customer model. The model will have following schema name: { type: String, required: true }, phoneNumber: { type: String, required: true, unique: true}, email: { type: String, required: true, unique: true}, streetAddress: { type: String, required: true }, area: { type: String, required: true }, city: { type: String, required: true }, state: { type: String, required: true }, postcode: { type: String, required: true }, country : { type: String, required: true },

    • Use modular architecture in server
    • Email should be valid format and unique (must be checked before calling save to server)
    • Follow existing work patterns (user or permission module works)
    • no need to apply authorization middleware. We will do authorization in different task

    Special note for devs:

    • I Will update this issue if needed. Please drop a comment if you are unclear about anything
    • You can include your friends in your forked repository so that you can work faster and can send the PR together
    opened by foyzulkarim 0
Releases(v1.0)
Owner
Foyzul Karim
Technology Explorer, Software Maker, Entrepreneur, Technology Coach.
Foyzul Karim
Postgres Node.js Express TypeScript application boilerplate with best practices for API development.

Node TypeScript Boilerplate Postgres Developer Ready: A comprehensive template. Works out of the box for most Node.js projects. This project is intend

Chirag Mehta 9 Aug 28, 2022
A boilerplate for building production-ready RESTful APIs using Node.js, Express, and Mongoose

By running a single command, you will get a production-ready Node.js app installed and fully configured on your machine. The app comes with many built-in features, such as authentication using JWT, request validation, unit and integration tests, continuous integration, docker support, API documentation, pagination, etc. For more details, check the features list below.

Hagop Jamkojian 5k Dec 31, 2022
React Native Boilerplate - The Boilerplate contains all the basic packages, common components and, prebuilt code architecture

The Boilerplate contains all the basic packages, common components and, prebuilt code architecture. It will save developer's project setup time.

MindInventory 36 Dec 26, 2022
Solana Boilerplate - Lightweight boilerplate for Solana dapps. Allows quick building and prototyping.

Lightweight boilerplate for Solana dapps. Allows quick building and prototyping. Feel free to contribute or fork this repository. Make it yours! Leave us a ⭐️ if this repo helped you.

null 21 Nov 15, 2022
A Node template that follows the Clean Architecture principles and encourages established practices.

Clean Architecture Template A Node template that follows the Clean Architecture principles and encourages established practices. Features TypeScript f

Jamie Livingstone 91 Dec 25, 2022
A highly opinionated and complete starter for Next.js projects ready to production

The aim for this starter is to give you a starting point with everything ready to work and launch to production. Web Vitals with 100% by default. Folder structure ready. Tooling ready. SEO ready. SSR ready.

Fukuro Studio 28 Nov 27, 2022
A Netflix clone created with the MERN Stack

X-Netflix X-Netflix is a streaming platform based on Netflix UI: built with ReactJS in frontend and nodeJS in backend. Built with FrontEnd: React.JS,

Mehdi BHA 52 Aug 19, 2022
This is a template project demonstrating how the MERN stack(Mongo, Express, React, Node) can be used, here we have the back end implementation and there is the React implementation as the front end

Versão em português MERN stack This is a template project demonstrating how the MERN stack(Mongo, Express, React, Node) can be used, here we have the

Douglas Samuel Gonçalves 2 Jan 22, 2022
An upgradable boilerplate for Progressive web applications (PWA) with server side rendering, build with SEO in mind and achieving max page speed and optimized user experience.

React PWA v2 A highly scalable, Progressive Web Application foundation,boilerplate, with the best Developer Experience. Demo: https://demo.reactpwa.co

Atyantik 2.5k Dec 26, 2022
A boilerplate for Node.js web applications

Hackathon Starter Live Demo: https://hackathon-starter.walcony.com Jump to What's new? A boilerplate for Node.js web applications. If you have attende

Sahat Yalkabov 34k Dec 28, 2022
React Starter Kit — isomorphic web app boilerplate (Node.js, Express, GraphQL, React.js, Babel, PostCSS, Webpack, Browsersync)

React Starter Kit — "isomorphic" web app boilerplate React Starter Kit is an opinionated boilerplate for web development built on top of Node.js, Expr

Kriasoft 21.7k Jan 1, 2023
React + Redux starter kit / boilerplate with Babel, hot reloading, testing, linting and a working example app built in

A comprehensive starter kit for rapid application development using React. Why Slingshot? One command to get started - Type npm start to start develop

Cory House 9.8k Jan 3, 2023
DDD/Clean Architecture inspired boilerplate for Node web APIs

Node API boilerplate An opinionated boilerplate for Node web APIs focused on separation of concerns and scalability. Features Multilayer folder struct

Talysson de Oliveira Cassiano 3k Dec 30, 2022
NextJS, TypeScript and Styled Components project boilerplate

This is a Next.js project bootstrapped with create-next-app. Getting Started First, run the development server: npm run dev # or yarn dev Open http://

Mateus 2 Sep 21, 2021
A boilerplate to kick off any Gatsby project.

A boilerplate to kick off any Gatsby project. This starter ships with: - Gatsby v4 - Material UI v5 with light/dark mode and a custom theme - Emotion JS (with access to Material UI custom theme) - React redux (with reduxjs/toolkit) - React intl for multilingual support - React helmet for SEO

Mario Duarte 1 Jul 6, 2022
Jekyllist - Modern Boilerplate on Jekyll

Jekyllist - Modern Boilerplate on Jekyll Jekyllist is a production ready boilerplate for humans who wants to build simple websites (portfolio sites, b

Atakan Oz 2 Jul 21, 2022
Very minimalistic boilerplate to start most Typescript Express projects. Includes Mongodb connection via Mongoose with a sample post model.

Minimalist express-typescript-boilerplate Available Scripts - `tsc' - builds the tsc project to the dist folder - `build` - cleans the previous build

Black Axe 16 Dec 13, 2022
Express typescript boilerplate using @types/node, @types/express

Express framework boilerplate in typescript.

Harris Gurung 3 Sep 21, 2022
Vite Electron Builder Boilerplate

This is template for secure electron applications. Written following the latest safety requirements, recommendations and best practices.

Harry Hopkinson 4 Dec 15, 2022