Securing a Chat App With React and Auth0
In this tutorial, we will build a chat application that’ll allow users to participate in a group discussion similar to how channels work in Slack. We’ll handle user authentication, and management using Auth0's Authentication-as-a-Service solution that allows developers to add authentication to any application without breaking a sweat easily.
At the end of this article, you will have a working application that looks like this:
Before you proceed with this tutorial, make sure you have Node.js and npm installed on your machine. You also need to have a basic familiarity with building Node.js and React applications. However, no prior experience with Stream Chat or Auth0 is necessary.
Sign up for Stream
Go here to create a free Stream account or login to your existing account. Once you’re logged in, you can save the application access keys from the app that's automatically created for you. Or, if you prefer, go to the dashboard, hit the blue “Create App” button at the top right of the screen and give your app a name as shown below:
Once you have created your application, you will be presented with your application access keys, which we’ll be making use of soon.
Set up the Chat Server
Fire up the terminal on your machine, and create a new directory for this tutorial.
cd into it and run
npm init -y to initialize a new Node.js project. We’ll be using express to set up a simple server for generating tokens that will be used for authenticating users. To install all the necessary dependencies which we’ll be using on the server, run the command below from the project root:
npm install express cors body-parser dotenv stream-chat --save
Once the dependencies have been installed, create a
.env file and paste your Stream application credentials into the file in the following format:
Following that, create a new
server.js file in your project root, and enter the following code into it:
In the above file, we have a single
/join route, which expects a username from the client-side and creates an authentication token for the user. The call to
updateUser() creates the user on our Stream chat instance, passing in the token for the user. By default, user tokens are valid indefinitely. You can set an expiration on a token by passing the number of seconds till expiration as the second parameter.
After creating the user, we initialize a channel of the type
id is set to
team chat type is just one of the five default channel types on Stream Chat and provides a good number of defaults for group messaging applications. The other chat types are livestream, messaging, gaming, and commerce. You can also create your own types for specialized use cases.
create() method, we set the creator of the channel to an
admin user. Lastly, we add the newly registered user as a member of the channel before sending the authentication token back to the client. Now, whenever a user registers within our application, they’ll automatically be added to the channel.
Before moving on to the next section, make sure to start the server on port
7000 by running
node server.js in the terminal.
Set up a New React App
Let’s create a new React application to showcase an exhibition of Stream’s React chat components, which makes building a custom chat solution a breeze.
npx create-react-app client in your project root to set up a new React project and install all the necessary dependencies. Next,
cd into the newly created
client directory, and run
npm start to start the development server. This should open up a new tab in your browser at
Sign up for Auth0
As mentioned earlier, we’ll be using Auth0 to authenticate users before they’re able to join our chat application. Head over to the Auth0 website and sign up for a free account. Once you’re logged in, you will be asked to choose a Tenant Domain and the region where your data will be hosted. Following that, you’ll need to create your first application.
To do so, hit the CREATE APPLICATION button and give your application a name. Also, select the Single Page Web Application option under Application type. Finally, create the Create button to create the application.
Once your app is created, find the Settings tab and enter your application URL (
http://localhost:3000) into the fields labeled Allowed Callback URLs, Allowed Web Origins, and Allowed Logout URLs.
Allowed Callback URLs is a whitelist of URLs that the application is allowed to redirect to – for example,
https://getstream.io/chat/redirect?foo=bar. Failure to set this will prevent users from being logged in. Likewise, Allowed Logout URLs is a whitelist of the URLs that the application can redirect to when someone logs out. Setting your application URL under Allowed Web Origins allows the application to refresh the authentication tokens automatically, otherwise, users will be logged out immediately they refresh the page.
Set up Authentication for Your React App
From within the
Following that, create an
auth0.js file in the
src directory, and populate it with the following code:
The above code provides a set of React hooks that allow you to log a user in or out. We’ll explore how to use these hooks in the next section.
One more thing to do here is to wrap our components with the
Auth0Provider component created above. This makes any component inside this wrapper able to access the Auth0 SDK client.
client/src/index.js and change it to look like this:
You can grab your domain and client ID from under the Settings tab in your Auth0 dashboard. Replace the placeholders above with the appropriate values.
Sign up and Login
When a user lands on the application page, they should be redirected to a page where they can register as a new user or login as an existing user. To achieve this, update your
client/src/App.js file as follows:
And update the
client/src/App.css file as well:
user allows us to determine if a user is logged in or not. As long as a user is not set, the current user is prompted to register or login using Auth0’s Universal Login Page.
When the user is logged in, control returns to the application, and a user will now be set. As is, nothing will be displayed when a user logs in. Let’s change that by utilizing the user profile retrieved from Auth0 to create a user on our chat application in the next section.
Add Chat Functionality With Stream
Go ahead and run the following command to install the additional dependencies needed to create our chat application. In addition to Stream’s API Client, we’ll be making use of ready-made React components that make setting up a beautiful and functional chat interface a breeze.
Next, create a new
Chat.js file in
client/src and populate it with the following code:
At the very top, we’ve imported a few components from the
stream-chat-react package. The
<Chat /> component acts as a wrapper and passes ChatContext to all other components.
<ChannelList /> is used to render a list of channels so you can select which one to join while
<Channel /> acts as a wrapper component for a channel. To render basic information about a channel – the list of messages in the channel and the text input – the
<MessageList />, and
<MessageInput />, components are used respectively.
Although Stream has a default
ChannelHeader component which you can use, a custom one is employed here to add a logout button that is not present in the default header.
By making use of Stream’s React UI Components, you get a lot of basic and advanced chat features for free such as typing indicators, emoji, reactions, file support, rich link preview, user presence (online or offline) and more which makes it easy to add in-app chat.
Update the App Component
The final step for this tutorial involves using the
ChatView component in
App.js as shown below:
This indicates that when a user is set (post authentication), the
ChatView component is rendered and the user is logged into our chat instance as seen in the GIF below.
In this tutorial, we explored how to make a secure chat application using Auth0, Stream Chat, and React. As you can see, building a secure user authentication flow in your Chat application is not hard at all with the help of Auth0’s robust solutions, and Stream’s React components make implementing complex chat features trivial.
You can build on the knowledge gained from this tutorial to build a chat solution that solves a real-world problem. You can check out other functionality Stream Chat offers by viewing its extensive documentation.
The complete code for this tutorial can be found on GitHub.
Happy chatting! 💬