How to prevent access to admin pages using Node.js and React.js ?
In many websites, the content available to the end-user is limited until he/she proves his/her authenticity by logging in. During the development of MERN Stack Applications, when the server is linked to the client, we may want to limit the pages accessed by the user unless he is logged in. In this article, let’s have a look at how to access admin pages is restricted using React.js and Node.js.
Modules Required on the client-side:
Modules Required on the server-side:
Client and Server setup:
Step 1: Create an npm repository using the command:
npm init --y
Step 2: Create a new react client project by using the command:
npx create-react-app client
Step 3: Create a server file in the current directory using the command:
Step 4: Switch to the src folder in the client folder and remove all the files using the following command:
cd client cd src rm *
Step 5: Create a pages folder in the src folder
Step 6: In the src folder create App.js, index.js, and PrivateRoute.js files.
touch App.js index.js PrivateRoute.js
Step 7: In the pages folder create Home.js Admin.js files.
cd pages touch Home.js Admin.js
Step 8: Install Axios and react-router-dom in the client folder
npm i axios react-router-dom
Step 9: Install express and cors in the server-side
npm i express cors
Project Structure: The file structure in the project will look like this.
Step 10: Editing index.js to link the HTML file and react libraries.
Step 11: Editing Home.js to illustrate a basic Home Page
Step 12: Editing Admin.js to illustrate a basic Admin Page
Step 13: Creating a private route that prevents webpage access to unauthorized users. This route can be used for any component which needs to be protected. The private route essentially makes an API call to the server to check the user’s authenticity. If successfully authenticated, the route renders the supposed component else it redirects to the home page.
Step 14: Integrating all the components in the App.js file. Routers are used to navigate between the home page and the admin page. We will create a button component to login and logout. Link tags are created for navigation purposes. Local Storage is used to sustain the login state between subsequent re-renders.
Step 15: Creating the server and listening to incoming requests on port 8000. We have created a middleware function to authenticate the user. This middleware function can be applied to any route.
Steps to run the application:
Run the following command in the client folder
Run the following command in the base directory
If everything is working as intended, we should be seeing:
- The following output on the server-side when we logout and login
- The following output on the client-side when we logout and login