Auth-middleware in Node.js
The term “auth-middleware” stands for authentication middleware which denotes verifying a user to access the web page or its APIs. We can prevent our website and the api endpoints from random users to use it by providing a layer with authentication and the code used for this protection is called the middleware.
Features of Authentication Middleware:
In order to provide authentication to the user, we need to generate a unique token for each user. The tokens are passed in headers for verification at the server. Basically the token is passed as “x-auth-token”.
In general, the auth-middleware ensures the following:
- A token is attached with the request
- The attached token is valid
- Access is provided for valid user
- Invalid users are restricted from accessing the endpoints.
Authentication in Node Js:
Lets consider an example here. In front end, a token is generated by using a secret key for each userID and attached with the request made to the server. The backend server in turn checks for the attached token in the request by generating the token for the userID with the same secret key. It compares the generated token with the token received. If both the tokens are matched, user is allowed to access the endpoints and if not matched, user is restricted and throws error to check the credentials.

The token is attached with the headers in the front end and the request is passed to the backend.

Here in Backend, token is generated using the secret key similar to frontend and both are compared for the validation. The server does the auth-middleware functionality as illustrated below:

If the token is compared and verified as valid, the user requests are allowed to access the endpoints and the responses are returned. If the token is found invalid, an error is thrown as “Authentication failed” and the user access to the endpoints is restricted.
In this way, auth-middleware is used to secure the endpoints by restricting from unauthorized access.