Building a React Login Page Template
- Category
- Guides
- Published
Discover how to create a secure login page for your React app with authentication, input validation, and styling.
React is a popular open source JavaScript library for building frontend applications and user interfaces. It offers a structured way of building web apps while retaining complete flexibility over the toolchains and integrations with other frameworks or APIs.
Simple to get to grips with and lightweight, React offers a range of benefits to developers—it's highly performant (reinforced by virtual DOM), it has reusable components that facilitate the quick scaffolding of large and complex apps, and last but not least, it offers solid support, including comprehensive documentation and a huge and active community of React developers.
One of the most integral parts of modern web applications is authentication, which not only helps you establish the identity of your users but also facilitates the implementation of roles and privileges to offer more control while maintaining security and abstraction.
However, implementing authentication in any web app from scratch can be a complex process. In this article, you'll see how to implement authentication in a React app manually by building a login page then adding input validation and styling. You'll then learn how to do it quicker by using Clerk to avoid the hassle of building the whole login flow from scratch.
Building a React Login Page
In this section, you'll see how to develop a custom React login page manually as well as add styling and validation. Once you get to the part where you need to add authentication, you'll make use of an Express-based auth server that uses JWT tokens to authenticate users. Finally, you'll see how to do the same using Clerk to avoid having to manually design the authentication flow.
The complete code for this tutorial can be found in this GitHub repo.
Prerequisites
To follow along with this tutorial, you need only Node.js and npm, the standard package manager for JavaScript.
Once you have these set up, start by creating a new directory for the project:
Next, create a new React app by running the following command:
Once the app is ready, you'll need to install react-router
to help set up page routing. You can do this by running the following commands:
You'll also need a basic auth server to set up authentication in your app. You'll need to create an Express app in Node.js, which you can do by running the following commands:
The auth server will use the following dependencies to set up JWT-based authentication:
- bcrypt: for hashing and comparing passwords
- jsonwebtoken: for generating and verifying JSON web tokens
- lowdb: for storing user details (email and hashed password)
You can now proceed with creating the React application.
Create a Welcome Page
First, you'll need a welcome page for your home route (http://localhost:3000/
). You can use the following code snippet by saving it in a file called home.js:
Update the code in App.js to set up page routing and add the home
route. Also, add a login
route, which will house the login page:
Once the home page is ready, it will look like this:
It will render a Log in button if you're not logged in, which upon clicking will lead you to a login page (which you'll create in the next step).
If you're logged in, it will render a Log out button with your email address, as displayed below:
Create a Login Page
Once your home page is ready, the next step is to create a login page. In this section, you will create and style a login page.
Create a Simple Login Page
To get started, save the following code snippet in login.js:
This will create a simple login page with two fields—email and password—and a login button. However, you'll also need to add some styling to this page to make it look better.
Add Styling to Your Login Page
To add some basic styling with CSS, paste the following code snippet in App.css:
Also, update the styles in index.css with the snippet below:
This is how the login page should look like:
The next step is to add some basic validation to the login form.
Add Validation
You'll notice that the code for the login form already contains <label>
components right below the <input>
components. You'll use these labels to show validation errors to users. The labels have already been styled in the stylesheets you saved above.
All you need to do now is to write the validation logic. Update the onButtonClick
function in the login.js file with the following code:
You can run the app with the following command:
You will now see validation errors pop up when you enter invalid input in the form.
This completes the frontend setup for the app. Next, you'll set up the auth server that will create and verify users with JWT tokens, and finally, you'll connect the auth server and the React app to see the system in action.
Set Up Authentication
The auth server will contain four API routes:
- GET at
/
: a basic home route with some info about the API - POST at
/auth
: an endpoint that will create and log in users and issue JSON web tokens - POST at
/verify
: an endpoint that will help verify JSON web tokens to see if they are valid - POST at
/check-account
: an endpoint that will check if a given email address has an associated entry in the auth database
Create an app.js file in your auth-server
directory. Before writing the code for these endpoints, you will need to add the following imports and other boilerplate code to your newly created app.js file:
You will also need to create a database.json file with the following contents in your auth-server
directory:
Now, you can start creating each of the four endpoints.
- The first endpoint (
/
) is fairly simple:
- The
/auth
endpoint is slightly more complex:
- The
/verify
endpoint simply checks for the validity of the supplied JWT token:
- The
/check-account
endpoint queries the database to see if an entry exists:
Finally, add the following line to start the server:
You can now run the following command in the auth-server
directory to start the auth server:
Make API Calls to the Server from the Frontend
The final step before you can see your React login system in action is to make API calls from the React app.
Update the onButtonClick
function in login.js in the frontend/src
directory to add the following call at the end (right after the validation code):
Define the checkAccountExists
and logIn
functions below the onButtonClick
function:
Next, add a useEffect
call in the App.js component to check if a user is logged in when the app loads:
Note: Make sure to add import { useEffect } from 'react';
at the top of the file to import the method.
Finally, update the onButtonClick
function in the home.js
function to correctly handle login and logout cases:
This completes the setup of basic JWT-based auth in a React app. Let's test it out in the next section.
Test the App
Navigate to the home page of the app by opening http://localhost:3000 in your web browser.
Note: Make sure that both your frontend and your auth server are running.
You should see the home page of the app. Click Log in to be taken to the login page. Enter any email and a password (minimum of eight characters) and click Log in. If successful, you'll be redirected to the home page, and your email will be displayed below the Logout button.
Note: The password as shown on the above screen is for demonstration purposes only. When building a login form in a real-world app, make sure to add type="password"
in the <input>
tag's attributes to mask the password characters entered by the user.
Click Log out to log out of the app. Before doing so, you can also try refreshing the app or navigating to the app in a separate tab/window to see if your user session is retained successfully.
You've now learned how to set up auth using React and an auth server written in Node.js and Express. However, this method was quite complex and needed a lot of manual design and implementation to get things right. And there are additional considerations when deploying and hosting your auth server to avoid security issues that this tutorial hasn't covered.
In the next section, you'll see a much simpler method of setting up authentication in your React app using Clerk.
Set Up React Authentication Using Clerk
Setting up authentication in a React app with Clerk is quite straightforward and friction-free. The following sections will help you get started with Clerk in the same React app you created above.
Set Up a Clerk Account and a Clerk App
Before getting started with the code, you'll need an account with Clerk. Create a new Clerk account if you don't have one already.
Once you're logged in, head over to the Clerk dashboard and click Add application.
On the next page, enter a name for your app (you could go with something like "React Login Demo") and click Finish, leaving the Email address and Google switches turned on.
Once the app is created, you'll be redirected to the app details in the Clerk dashboard. Click on the API Keys option under Developers in the left navigation pane.
This is where you'll find your Clerk app's publishable key. You'll need this key to integrate and use the Clerk SDK in your React app. Copy and store it as a .env
file in your React app's root directory.
Now you can go ahead and set up the Clerk SDK in your React app.
Install Clerk Dependencies and Configure Login Page
To get started with Clerk in your React app, install the Clerk SDK by running the following command:
Make sure you've stored the publishable API key in a .env
file at the root of your frontend project.
Now, you can import and use the components provided by Clerk to easily set up authentication.
To begin, wrap the root component of your app (which you'll find in the index.js file) with the ClerkProvider
component. Here's how your index.js file should look like when done:
Next, head over to the home.js
file and update it to look like the following:
That's it! That's how simple it is to set up auth using Clerk.
To clean up your app, head to the App.js file and remove the useEffect
call that checks for the existing user using the old, basic method. You could also remove the /login
route as the Clerk method has no use for it.
Testing the Clerk Method
To try out the Clerk method, start the React app using npm start
(stop and start it if it's running already so that the env value is loaded correctly). You'll see the same Log in button as before.
Once you click it, you'll be redirected to the Clerk sign-in page, where you can log in using an email or your Google account. Once you've logged in, you will be redirected back to the home page of your app, and the logged-in user's email will be shown.
As you can see, setting up authentication with Clerk is far easier and simpler than the manual approach. You don't need to worry about maintaining user data in your database, and you can easily integrate third-party login methods (such as Google, Facebook, etc.) without having to set up their SDKs individually. The auth components offered by Clerk are tailored to make lives easier for React developers.
Once again, the code for this tutorial can be found in this GitHub repo.
Conclusion
React is one of the most versatile JavaScript-based libraries for building frontend web applications. In this article, you saw how to create a login page in a React app, add input validation, style the page, and set up an auth server in Node.js to handle authentication using JWT. Next, you saw how to do the same using Clerk, a modern user management platform built specifically for React and Next.js.
Clerk makes authentication and user management simple. It offers a wide range of customizable components to quickly integrate into your app. You can also use the hosted sign-in flow, as you saw in this article, to save yourself the effort of building and maintaining a sign-in flow. Make sure to sign up for Clerk to try it out in your React apps.
Ready to get started?
Start Building