Image for post
Image for post
Developing Modern Apps with Symfony and React

TL;DR: In this post, you will learn how to develop web applications using React and Symfony. Moreso, you will also learn how secure both the frontend and backend of the application by adding authentication and authorisation using Auth0. React will be used to power the frontend logic of this application while Symfony will be used to build the backend API. The complete source code for this post can be found here on GitHub.

Check out the Auth0 Blog 🔐 and find everything you need to know about Identity Infrastructure, Access Management, SSO, JWT Authentication, and the latest in Security. 👉 AUTH0 BLOG 👈


To get the best out of this post, a reasonable knowledge of React, Object Oriented Programming in PHP, JavaScript and a basic knowledge of building applications with Symfony is advised. Another important factor is for you to ensure that you have Node.js and Yarn package manager installed in your development machine. If you are yet to get them installed, kindly check this link to learn how to properly install Node.js and here for Yarn package manager. Lastly, you also need to install Composer.

What is Symfony

Symfony is a set of reusable PHP components, the leading PHP framework to create websites and web applications. It has an elegant structure and it is known for being a suitable framework to bootstrap any web application project regardless of the size, from small to a large scale complex applications.

For additional information and a deep dive into more concepts and philosophy of Symfony, visit its official documentation.

What is React

ReactJS is an open-source JavaScript library popularly used for building dynamic and decent user interface for single page applications. The simplicity and incredible performance of applications created with React make it a top choice by most web developers and reputable companies. Developed and maintained by Facebook and with commendable numbers of stars on GitHub, React has really enjoyed a wide adoption from the web tech community.

While developing applications with React, it is absolutely necessary to put into consideration the basic concepts considered as best practises and extremely crucial to successfully craft a top-notched React app. If you are new to React and will like to easily get yourself familiarised with some of these core concepts of creating modern reusable user interface with React, check out this comprehensive article on building and securing your first React app.

Combining React and Symfony

Contemporarily, modern web applications built with PHP framework like Symfony now require implementation of a huge amount of logic on the frontend in order to create a rich web experience for users. This is mostly handled by jQuery back in the days, but at the moment, there are numerous awesome frontend libraries available in the market. They include, but are not limited to Angular, Ember, Vue and React. With these several options, one can easily get lost and spend quite a bit of time deciding on which of the library is more compatible with Symfony.

To make things easier, Symfony unlike its major contender in the PHP world (Laravel), does not favor a particular library or frontend framework over another. It remains absolutely neutral to your choice of the library that runs on the client side of your application. This leaves you with an opportunity to explore the world of JavaScript and work with any of the modern frontend library for building single page applications that you are quite comfortable with.

However, as at the time of writing, React is the most prominent library for building reusable user interface components. As you proceed with this post, you will realise how easy it is to combine React and Symfony together in a single project successfully. Thanks to the introduction of a pure-JavaScript library called Symfony Webpack Encore, it is now simple to manage JavaScript files in a Symfony-based application, as it offers a simplified process for working with both CSS and JavaScript.

What You Will Build with React and Symfony

As pointed out at the beginning of this post, you will learn how to build a secured application with React at the frontend and a Symfony powered backend API. This application will allow users to fetch protected information from the API only if they are authenticated and give full access to a public route for all users ( authenticated and non-authenticated) as depicted by the images below:

Traditionally, Symfony usually handles everything from the state management, page rendering and routing when developing web applications with it. Here, you will deviate a little from totally building Symfony applications that way, as you will learn a different approach to page rendering, routing and state management.

Structure of the application

The frontend of the application will be broken into different reusable and independent UI components. Here, you will use React to render contents without necessarily requesting a new page from the server or refreshing the page before navigating to a new route. This is one of the beauties of single-page applications.

Once a user tries to fetch information from a protected route, that will be defined later in this post, they will be redirected to Auth0 to get authorized and afterwards, they will be redirected back to the app.

For the backend, you will simply use Symfony to accept and process HTTP requests sent in by React and return the appropriate information based on the authentication status of the user.

With the structure and basic information about the application that will be built in this post properly covered, you can now proceed to start building the application.

Scaffolding the Symfony Application

Here, to start building the backend API, you will install and set up a Symfony application via Composer. To do this, you need to access the terminal in your operating system, navigate to your development directory and run the following command to install a project named symfony-auth0-api on your machine:

Once the installation process of Symfony and the respective required bundle by Composer is completed, change directory into the newly created folder with:

Creating the Symfony Backend API

Leverage the Symfony maker bundle to create a controller for the API with:

The preceding command will create a new file named SecuredController.php which can be found in src/Controller folder and a template file in templates/secured/index.html.twig. You can ignore the template file for now, but open the newly created SecuredController.php and add the following content:

Here, you defined two different methods, a publicAction() and a privateAction(). They both returned different responses in JSON format. You can try this out using a tool called Postman. But before that, you need to start the application by running php bin/console server:run to start the development server on http://localhost:8000.

Next, try accessing the public route on http://localhost:8000/api/public. You will see the list of JSON data returned as a response for the public route as depicted by the image below:

Now, do the same for the protected route on http://localhost:8000/api/private. You will see the list of JSON data returned as response for the private route as depicted by the image below:

At the moment, the endpoint for both routes can easily be accessed by anyone. This is not ideal. You need to protect the private API by making its endpoint secured. Proceed to the next section to learn how to make your /api/private endpoint secured by adding authentication and authorization. You will need an Auth0 account for this purpose, create a new account if you don’t have one already.

Securing the Symfony API with Auth0

In the previous section, you created a controller for the API and added some dummy data that will be displayed for both the protected and public route. To secure these APIs, you will need to head back to your Auth0 dashboard and configure an API. What this means is that you will have to create a new API on Auth0 and integrate it with your Symfony application. This, among other things, will leverage on Auth0 to issue JSON Web Token for your application and make it more secured.

To begin, head to the API section of your Auth0 management dashboard and select APIs. If you have created APIs before now, this will show you the list of all APIs for your account, but for the purpose of this tutorial, go ahead and click on the CREATE API button and set up a new one. Next, provide a friendly name as you deem fit for your API. I have intuitively named the API for this demo as webby-api. In addition, also ensure that you set an identifier as this will be used as audience later when you are configuring the Access token, I currently used http://localhost:8000/api for mine. You must leave the signing algorithm as RS256 and then proceed to click on the CREATE button.

Validating Access Tokens

How this will work is, whenever a user tries to access a protected endpoint of your custom API, an authorization header with a bearer access token will be sent alongside the HTTP request. Once this access token has been validated appropriately, the resources protected by such endpoint will now be made available to such user.

Protecting a Symfony API with Auth0 requires that you install auth0/jwt-auth-bundle package. But before that, stop the process that is currently running by pressing CTRL + C. Next, run the following command to install the jwt-auth-bundle for your project:

Once the installation process is complete, you will need to add configuration value for the newly created bundle. For this, navigate to /config/packages folder and create a new file named jwt_auth.yaml. This file will hold three different required values for your API. Open the newly created file and paste the following content in it:

Note that, you will need to replace the YOUR_AUTH0_DOMAIN with the appropriate value from your application dashboard. Earlier, when you created an API, Auth0 also automatically created a test application for you to use. This will be the Auth0 application that will hold your users. In order to view your applications, click on Applications from the menu items and you will see the list of all applications on your Auth0 management dashboard. You can also select and use any other applications for your account. But for the purpose of this tutorial, click on the test application and you will see a page as shown here:

You can copy the domain from the test application and use it to replace YOUR_AUTH0_DOMAIN placeholder (e.g.

Now, that you are done creating an API, installing the jwt bundle to validate users and adding the appropriate credentials to configure the bundle for your application properly, you can now proceed to the next section and create a User class alongside a User provider.

Set Up User and User provider, and configure security provider

For a typical Symfony application a User class is always required and for each User class in your application, there is a need to set up and configure a user provider. A user provider, among other things, helps to reload a user from the session and load users for other login specific features like using username or email for authentication.

Here, you will need to create a custom user provider class since you will be loading users from a custom location (via Auth0) and not from your application’s database. To begin with, navigate to the src folder and create a new folder named Security and within the newly created folder, create another one and call it User. Next, create the user class within the User folder and name it WebServiceUser.php. Open the newly created file and paste the following code in it:

Here, the WebServiceUser class implements two different interfaces namely:

  • UserInterface: which represents the interface that all User classes must implement and
  • EquatableInterface: which is used to test if two objects are equal in security and re-authentication context

With that completed, create another file within the User folder and name it WebServiceUserProvider.php. Use the content below for it:

This class implements the JWTUserProviderInterface from the Auth0 bundle installed earlier which specifies the important methods that the WebServiceUserProvider class must implement. These methods are:

  • loadUserByJWT: it receives the decoded JWT Access Token and returns a User.
  • getAnonymousUser: returns an anonymous user that represents an unauthenticated one (usually represented by the role IS_AUTHENTICATED_ANONYMOUSLY)

To wrap things up for the user, create a file that will return the anonymous user within the User folder and name it WebServiceAnonymousUser.php. Use the following content for it:

Configure the Security Provider

You are almost done with the API security configuration, the last thing you need to do is tell Symfony about the user class and provider and also configure the access control. These configurations will be done by modifying the security.yaml file located in config/packages folder, but before that, you need to set up a service for WebServiceUserProvider.

Services are a great way to make your applications easier to maintain and adapt to new requirements. You can create one by adding this code to the bottom of config/services.yaml file:

Lastly, modify the security.yaml file located in config/packages/security.yaml file such that it contains the following:

  • The web_service_user_provider service
  • The secured area that you want to authenticate using an Access Token
  • The access_control section with the roles needed for each route

Now you are done securing the API. You can test this again with Postman by accessing the protected route. Start the application by running php bin/console server:run and access http://localhost:8000/api/private. You will receive a message indicating that you do not have access to such endpoint as shown below:

You can now proceed to the next section where you will set up the frontend of the application with React.

Building the Frontend App with React

Here in this section, you will download and install React. To begin, stop the process that is currently running by pressing CTRL + C, then run the following command from the terminal and within your project directory to install React, Webpack Encore and other dependencies using Composer:

The preceding command will carry out the following tasks automatically:

  • Create a webpack.config.js file
  • Add the assets directory
  • And finally, add node_modules folder to the .gitignore file

Once the installation process is complete, use Yarn to install React, React-router and other dependencies

Configuring Webpack Encore

Configure Webpack Encore by enabling React and adding the entry point within the webpack.config.js file at the root of your project as shown here:

With webpack.config.js file properly configured, as shown above, you now have an entry point (i.e., addEntry()) method that tells Encore to load the assets/js/app.js file, which was automatically created to manage all javaScript related files.

You can now proceed to the next section where you will start creating reusable components for the application.

Building React components

Now that you have installed React successfully, you will need to create a couple of React reusable components to help with a better structure for the application. To begin, create a new folder inside assets/js folder and name it components. This newly created folder will house all the reusable components for this application.

Next, within the components folder, create the following JavaScript files:

  • Home.js: This component will be the homepage for the application and be used to display the contents from the public route to users.
  • NavBar.js: This component will handle navigation for the frontend of the application
  • privateResources.js: This will be used to fetch the private resources from the protected route of the API and display it to the users.
  • publicResources.js: This will fetch the resources from the public route for all users.
  • SecuredRoute.js: This file will be used to check if a user is authenticated and routed to the protected component.
  • Callback.js: This component will process the redirect from Auth0 after a user has been authenticated. It will be activated at the http://localhost:8000/callback endpoint.

The Home component

You can now start with the HomeComponent by opening the assets/js/components/Home.js file created earlier and add the following code:

Here, what you have done is to import the required modules (some of the files will be created later in this section), used one of React’s lifecycle methods to check whether the requested route is /callback. If it is, the Callback.js component created earlier will be used to handle the authentication process.

Later in this component, within the render() method, you have included the NavBarComponent and used React-Router to render the appropriate components. Did you notice the SecuredRoute component? it was used to ensure that only authenticated users can access the /private endpoint. You will create it later in this post

Lastly, you enclosed the HomeComponent class inside the withRouter method in order the check the router being called.

The Navigation bar

In the last section, you imported and included the NavBarComponent with the HomeComponent. Here, you will open the NavBar.js file created earlier and paste the following content in it:

You imported the auth0Client from a utils folder. This is a helper class that will be used to handle authentication for the frontend of this application. There will be more details about it in the next section.

The Auth Component

This component is an helper file that will help with the authentication flow. This will give the application a meaningful structure for authentication. Before you create this file, you will have to install a library provided by Auth0 to secure single page applications. It is called auth0-js and you can install it now using Yarn package manager:

Next, create a utils folder inside assets/js and create a new file named Auth.js inside of it. Once you are done, paste the code below in the newly created file:

Here, you instantiated the auth0.WebAuth and included the required configuration from your Auth0 management dashboard. So far, you have a YOUR_CLIENT_ID and YOUR_AUTH0_DOMAIN, however, there are other configurations that you still need to include for your application to work properly.

To complete this, head back to your applications dashboard and click on the test application created by Auth0 as you did earlier in this post. This will by default opened the settings tab. Next, search for Allowed Callback URLs field and insert http://localhost:8000/callback in it. This is quite important as users of your application will only be redirected back to the endpoint specified for this field after authentication.

There are two important configuration properties to change before saving the changes. Look for these fields and insert the respective values:

  • Allowed Web Origins: add the following http://localhost:8000 and
  • *Allowed Logout URLs*: This will be a log out endpoint that will be used to end user’s session on Auth0, so update the field with http://localhost:8000/logout

Note: Don’t forget to replace the YOUR_CLIENT_ID and YOUR_AUTH0_DOMAIN placeholder with the appropriate credentials

Handling Public Resources

Next, open the publicResources.js file and use the content below for it:

The component file above is responsible for fetching resources from the http://localhost:8000/api/public endpoint once the page is fully loaded and displayed it to the users. There is no need to check if the user accessing this endpoint is an authenticated user as it is a public route.

In the next section, you will set up the privateResources components.

Handling Private Resources

To set up this component, open the privateResources.js file created earlier and paste the following content in it:

This file is responsible for fetching resources from the http://localhost:8000/api/private endpoint and unlike the public endpoint, it requires that a user with the right authorization can only be allowed to view its contents.

Here within the fetchPrivateResources() method, an authorization header containing the Bearer token was passed alongside the HTTP request. Without the bearer token, the request will be denied as it is being expected by your Symfony API.

Add a Callback Component

This component will be activated once the /callback endpoint is called. The /callback endpoint would normally be called only when a user has been authenticated on Auth0 and redirected back to your application. You will still need to import and make use of the Auth helper class created earlier for authentication within this component. Open callback.js file within assets/js/components folder and paste the following code:

Auth0 will redirect back to your application once a user is authenticated and call the /callback route. This will come with an id_token as well as the access_token for the particular request.

Secure the protected route

To secure the protected route and ensured that only authenticated users could access it, you wrapped it The file for this component has been created earlier. It can be found in assets/js/components/SecuredRoute.js. Open it and insert the following content:

Modify the App component

You need to make little modification to the AppComponent for the application. To do that, open assets/js/app.js and update as shown here:

Creating the Default Controller

Finally, before you test the application head back to your Symfony application and use the maker:bundle to create a default controller for the application. This new controller will be responsible for rendering the pages. Run the following command for that purpose:

This will create a new file named DefaultController.php within /src/Controller and a template file within /templates/default/index.html.twig.

First, open the DefaultController.php file and edit as shown below:

What you have done differently from a typical Symfony controller is the addition of a parameter (reactRouting) to the URL within the controller. This included parameter will allow React router to control routing within the application and stop Symfony from intercepting the route.

Rendering the React application

Locate the template for the default controller within templates/default/index.html.twig and paste the following:

This is the template file that will render the React application within Symfony.

Updating the Base template

Navigate to templates/base.html.twig and update it with the following code:

What you have done here is to include a CDN file for Bootstrap, Font Awesome and the file for React as compiled by Webpack Encore.

Running your React and Symfony App

You can now run the application to test the functionality. First, start Symfony application by opening the terminal from within your project directory in case you have closed it already:

Next, open another terminal and run the following command to compile the React application and watch the JavaScript files for any changes:

Navigate to http://localhost:8000 to see the application.


This tutorial gives you an understanding of how to successfully craft an application that combines both Symfony and React together as a single project. This eliminates the worries about CORS (Cross-Origin Resource Sharing) as you can easily run the application from a single domain.

As shown here in this post, you have learned how to create APIs within Symfony application and integrate it with an API created on Auth0. You went further to learn how to properly secure your application by leveraging on Auth0’s API and application configuration services.

A modern single page application like what you have built in this post always requires the right tools in order to work properly by combining several components. Thanks to Auth0, you now have a more secured Symfony backend API with a secured React frontend. I hope you found this tutorial helpful.

Please Feel free to share your thoughts and questions in the comment section below.

Originally published at

Written by

Identity Is Complex, Deal With It. Auth0 is The Identity Platform for Application Builders.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store