Strapi Authentication with React

Create a React application with authentication and authorization using Strapi.

Strapi
Strapi
17 min readOct 24, 2022

--

Author: Sachin Chaurasiya

Any application with users requires authentication, but setting up a complete authentication and authorization workflow from scratch could be time-consuming and inefficient.

Strapi enables us to request data for our headless CMS API using multi-authentication providers like Google, Twitter, etc. Making it easier for authenticated users to perform actions only available to authorized users.

The Strapi authentication system allows us to quickly build a robust authentication system for our application. In this tutorial, we will create a simple React application that uses Strapi for authentication and authorization.

An Introduction to Headless CMS

The Content Management System (CMS) allows you to create and manage content for your website and applications. In a traditional CMS, the front-end and back-end of the website or application are integrated. Aside from pre-made themes and custom codes, there are no customization options. Traditional CMSes like WordPress, Joomla, and Drupal integrate the website’s front-end with the back-end.

A headless CMS lets you build out your client or front-end, connecting it to the CMS via APIs. With a headless CMS, the application front-end can be built using any technology, allowing multiple clients to connect and pull data from the same CMS.

An Introduction to Strapi

Strapi is the leading open-source, headless, customizable Content Management System. With Strapi, you can easily build custom APIs in REST or GraphQL that can be consumed by any client or front-end framework. We’ll be using Strapi API while building authentication and authorization with React.

Authentication and Authorization with Strapi

To authenticate users, Strapi provides two auth options: one social (Google, Twitter, Facebook, etc.) and another local auth (email and Password). Both of these options return a token (JWT token), which will be used to make further requests. JWT token contains user information and expiry which get validated for each request.

For authorization, Strapi has the Roles & Permissions plugin, which allows complete protection of your API by ACL strategy. ACL strategy manages the permissions between the groups of users. Each time an API request is sent, it checks if an Authorization header is present and grabs the JWT token which contains the user ID and verifies if the user making the request has access to the resource.

For this tutorial, we will be using local auth (email and password).

What is React?

React is a Javascript library for building a user interface with reusable components. In React, you write once and use it everywhere, resulting in less coding and faster development.

React has large community support and it’s used by giants like Facebook, Tesla, etc. React provides some outstanding features like JSX (Javascript syntactic extension), Virtual DOM (Document Object Model), etc. Click here to learn more.

Goal

At the end of this tutorial, we will have covered how to add authentication to our React application with Strapi.

Prerequisites

To follow through with this article, you need:

  • Basic knowledge of JavaScript
  • Basic knowledge of React
  • A code editor like VSCode
  • Node.js version (¹⁴.17.0, or >=16.0.0). You can download Node.js from Node.js official site if you haven’t already.
  • npm 7 or greater installed

What We’re Building

We’ll build a simple social card application, where users can register, log in, and edit their social cards.

Sample Screenshot
Sample Screenshot
Sample Screenshot
image.png

Setting up the Backend With Strapi

To get started, we will begin by setting up the backend with strapi.

  • Create the project directory:
  • Create the directory for the backend:
  • Create the directory for the frontend:

Our project structure will look similar to this:

project structure

Creating A Strapi Project

Change the directory to the backend and then run either of the commands to create the Strapi project in the current folder.

Note: . at the end is to tell the strapi-app script to create a project in the current folder.

Next, choose the installation type Quickstart. It uses the default database SQLite and is recommended. Once the installation is complete, the Strapi admin dashboard should automatically open in your browser. Fill out the details to create an admin account.

Strapi Admin

Modify User Collection Type

The collection is a table containing entity information. Strapi, by default, provides us with a User collection with minimal fields like username, email, password, etc. For this tutorial, we will be extending the User Collection by adding our fields.

Navigate to the Content-Type Builder > Collection Types > User .

Strapi Content-Type Builder Page

Now, we will add 7 more fields to this collection. Click on + ADD ANOTHER FIELD to add these fields.

  1. about (Rich Text) Advanced Settings:
  1. avatar_url (Text — short text) Advanced Settings:
  1. website_url (Text — short text) Advanced Settings:
  1. twitter_username (Text — short text) Advanced Settings:
  1. linkedin_username (Text — short text) Advanced Settings:
  1. github_username (Text — short text) Advanced Settings:
  1. profile_slug (UID) (Attached field — username)
image.png

Click on Save; this will save the changes to the collection type and restart the server.

Configure Permissions for Public and Authenticated Users

As Strapi is secure by default, we cannot access data from the API unless we enable permissions. To set permissions:

  • Navigate to Settings > Users & Permissions plugin > Roles.
  • Go to Public and enable the following actions for the User under Users-permissions.
  • Count ✅
  • find ✅
  • findOne ✅
Permissions Configuration
  • Click on Save and it will update the permission for public users.
  • Go to Authenticated and enable the following actions for the User , Auth and Permissions under Users-permissions.
  • Auth ( Select All ✅ )
image.png
image.png
image.png
  • Click on Save and it will update the permission for authenticated users.

Creating Data for the Application

You will need to create a few users for our application. To create new users, navigate to Content Manager > User and click on Create new entry. Fill out the required details and click on Save to create the entry.

user

The backend setup is done; now, move forward and set up the front-end of our application.

Setting up the Front-End with React

Change the directory to the frontend and then run either of the commands to create the react project in the current folder.

Note: . at the end is to tell the create-react-app script to create a project in the current folder.

Remove these files:

  • App.css
  • App.test.js
  • logo.svg
  • serviceWorker.js

Rename these files accordingly:

  • App.js → App.jsx
  • index.js → index.jsx

Install the Dependencies

For this application, we will be using antd for UI components, react-icons for icons, and react-router-dom for routing.

Let’s install them in our project.

Alright, we have our frontend set up is ready. Now, let’s code our social card application.

Setup Constant and Helper

Create a src/constant.js file and add the below content to it.

If the avatar URL is not available, then we will use the avatar API to get the avatar by username.

Create a src/helpers.js file and add the below content to it. These are the helpers that we will be using for managing the jwt token for the Authenticated user.

Setup the AuthContext

Create a React context to store logged-in user details. React Context is designed to store data which is global and shared between components. You can read more about the react context here.

Create a folder named context and create a file AuthContext.js.

After creating the AuthContext.js, add the code below content to it. Here, you are doing two things: first, we are creating the AuthContext to hold 3 things, user, isLoading and setUser method, and second, creating a custom hook by using the useContext hook with AuthContext, so that you can directly use this custom hook to get the AuthContext data.

Setup the AuthProvider

The next step is to create a provider component for the application which will use the above AuthContext. AuthProvider will be the wrapper component which will provide the authenticated user details.

This component will take one prop which is “children” and return it with AuthContext provider values. it will fetch the authenticated user details if the jwt token is present.

Now, replace the src/index.jsx content with the below content.

Here, you’re wrapping your App component with AuthProvider and Router Component to handle authenticated users and routing respectively.

Create AppHeader Component

The application provider has been set up now; let’s create a header component for our application.

Note: All of the CSS is available in the src/index.css file here.

The AppHeader component will render four links based on authenticated user data. If user data is present, it will render the user profile link and a logout link. Else, it'll render links for registering and login into the application.

Create SocialCards Component

This component will be responsible for fetching all the available profiles in our application and then showing social cards for all the profiles.

image.png

Create Register Functionality

You will start by creating the signup page component and there, add a form which will contain 3 fields: username, email and password. You'll use the custom hook, useAuthContext, to get the setUser method to set the Authenticated user data after a successful registration.

You’ll also use useScreenSize custom hook to get the user screen type. You can get the code for it hooks/useScreenSize.jsx. Once the user clicks on the submit button, it will call the onFinish method which will call the /auth/local/register endpoint with user data to create the user. On Success, you'll store the authenticated user data and jwt token and redirect users to their profile.

image.png

Create Sign-In Functionality

If the user already has an account, they’ll need a login form to authenticate the application. You’ll create a Sign-In page to handle that. Once the user clicks on the submit button, it will call the onFinish method, which will call the /auth/local endpoint with user data to create the user. On Success, it'll store the authenticated user data and jwt token and redirect users to their profile.

Sign-In Functionality

Add Edit Profile Functionality for Authenticated Users

The profile component will hold the authenticated user data and allow the user to update the data. Once the user is logged in to the application, it will redirect to the profile component and this route will be a protected route.

Edit Profile Functionality

There are four functionalities: register, login, logout and Edit Profile. The next step is to create routes for these and add them to the app component.

Add Routes

There’ll be four routes: home, signin, signup and profile ( protected ). For the profile route, there should be a condition that if the token is present, it should only render the profile component; otherwise it should redirect the user to the login page.

Configure App Component

Finally, change the content of App.jsx to the below content. It will render the AppRoutes component and everything will be taken care of by the AppRoutes.

Conclusion

So far, we have seen how to build a React application with authentication using Strapi as a headless CMS. Let’s summarize what we’ve been able to achieve so far.

  • You created and set up Strapi, configured the User collection type, and modified permissions for public and authenticated users.
  • You created a new React application with antd for styling.
  • In Strapi, you used the local provider (email and password) for authentication.
  • In React, you used local storage to store the JWT token, allowing authenticated requests to Strapi.
  • To store the authenticated user data, you used React Context.

There are probably a few things you learned from this tutorial that you can apply to your projects. The Strapi and React application source code is available on GitHub and listed in the resources section if you need them.

Resources

Here are a few articles I think will be helpful:

Here is the code for the React frontend and Strapi backend:

--

--

Strapi
Strapi

The open source Headless CMS Front-End Developers love.