This is a minimal example of authenticated communication between a React app and a node.js API using Auth0.
👉 Full-stack Demo 👈
(The demo connects to an api hosted on Replit).
The Quick Start below will get you up and running quickly but for a deep dive we recommend working through the official Auth0 React Workshop.
-
Fork this repo and open it up in an editor. Run
yarnto install dependencies. -
Visit Auth0 and set up a free account. Click
+ Create Applicationset the Application type toSPAset the application name toauth0-react-node-ts. Find the fieldsAllowed Callback URLsandAllowed Web Originsand set both to:
http://localhost:3000, https://add_production_url_here_once_deployed.com
-
You will see that Auth0 has provided you with a
Domainand aClient ID. Inside your app open/.env.exampleand set the Domain and Client ID. Rename the file.env(remove the.exampleextension). -
Next, we need an API to connect to. Visit the demo API hosted on Replit and fork the project. Inside your new forked Replit project, click on 'Secrets' and add the following.
key: AUTH0_DOMAIN
value: <your Auth0 Domain>
- Finally we need to connect the app to the API. Open your
.envfile and setREACT_APP_API_URLto point at your forked Replit URL (it will look something likehttps://auth0-react-node-ts-api--your_username.repl.co).
That's it, the app and the API can now communicate securely. Start your Replit API and run yarn start in your app to start the demo.
This is a high level flow diagram of how the app, the API and the authentication server work together to allow secure communication using tokens.
Keep in mind this is just the simplest example of a token being consumed by an API. There is no sign up flow, no database at all, we are not remembering our users or dealing with permissions. For a more complete solution check the Official Auth0 React Workshop repo.
Look at the Auth0 docs section on Sessions.
You have deployed your app to Netlify or Vercel but it throws an error when it tries to fetch the token? This is because you haven't told Auth0 where your application is deployed. Login to edit your Auth0 application settings. In the Quick Start we set Allowed Callback URLs and Allowed Web Origins to be:
http://localhost:3000, https://add_production_url_here_once_deployed.com
Edit these to replace https://add_production_url_here_once_deployed.com with the URL of your deployed app (aka https://myapp.netlify.com).
