A template for node express-mongo-rest-api backend. It is secured and fast. Global error handler, JWT authorization system, request rate limiter, best security practices for express are already setup in this template.
There is a Use Template
button on top of the repository page. You can generate your back-end by simply clicking the button.
Then create a .env
file. Look at the .env.example
file for help. Then run npm install
to install the required packages.
Now run npm start
to start the development server. You must have nodemon globally installed. to install nodemon globally, run npm i nodemon -g
use sudo
if you get any permission error.
Create a js
file inside the routes
folder and import the file in the routes/index.js
. Then create express route in your js
file. Have a look at the userRoutes.js
as an example.
Create your models inside the models
folder. Go to Mongoose Documentation for more information.
Create your controllers inside the controllers
folder. If you look at the userController.js
file, you'll see that I used a function called cathAsync
in every controller function. This is a helper function to avoid writing try-catch block
for every async function.
The Error Handler Middleware is used to capture all of the errors from any middleware or controller and send a response according to the error. Just use next(Error)
from any of the middleware or controller to use it. There are a class called AppError
extended from the Error
class for better error responses.
So you can use the error handler like this:
// Inside any middleware or controller
const error = new AppError(errorMessage, errorCode);
next(error);
If you want to limit the amount of request coming from any IP address you can use the limiter
middleware. To use this you have to set the environment variables RATE_LIMIT_RESETS_IN
(minute) and RATE_LIMIT
. Now add the limiter
middleware to any route you want.
This middleware is used to protect a particular route from unauthorized users. Add thr protect
middleware to any route you want.
I used JWT to do the authorization process. Send a post request to the /users/login
route with the email and password and a token will be sent in both cokkies (http-only) and response json. Now, you can use Bearer token or token in your cookie to authorize the user.
Any kind of contribution is welcome. Have a look at the CONTRIBUTING.md file for details.