The Complete Guide to React Authentication with Auth0

This should be sufficient and produce the results. Just point your api accordingly (for your env you’ll likely need some adjustments due to the different ports

requirements.txt

anyio==3.5.0
asgiref==3.5.0
click==8.0.3
colorama==0.4.4
fastapi==0.73.0
h11==0.13.0
httptools==0.3.0
idna==3.3
pydantic==1.9.0
python-dotenv==0.19.2
PyYAML==6.0
sniffio==1.2.0
starlette==0.17.1
typing-extensions==4.0.1
uvicorn==0.17.4
watchgod==0.7
websockets==10.1

main.py

from typing import Optional

from fastapi import FastAPI, Response

from fastapi.middleware.cors import CORSMiddleware

origins = [
    "http://localhost:3000",
]

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)





@app.get("/api/teleporters")
async def read_root( response: Response ):
    return {"Hello": "World"}


@app.get("/items/{item_id}")
async def read_item(item_id: int, q: Optional[str] = None):
    return {"item_id": item_id, "q": q}

run with

uvicorn main:app

reproduction steps

  1. shift f5 on profile page after login
  2. click protected routes
  3. observe fast api output
←[32mINFO←[0m:     Started server process [←[36m13092←[0m]
←[32mINFO←[0m:     Waiting for application startup.
←[32mINFO←[0m:     Application startup complete.
←[32mINFO←[0m:     Uvicorn running on ←[1mhttp://127.0.0.1:8000←[0m (Press CTRL+C to quit)
←[32mINFO←[0m:     127.0.0.1:58448 - "←[1mOPTIONS /api/teleporters HTTP/1.1←[0m" ←[32m200 OK←[0m
←[32mINFO←[0m:     127.0.0.1:58448 - "←[1mOPTIONS /api/teleporters HTTP/1.1←[0m" ←[32m200 OK←[0m
←[32mINFO←[0m:     127.0.0.1:58448 - "←[1mGET /api/teleporters HTTP/1.1←[0m" ←[32m200 OK←[0m
←[32mINFO←[0m:     127.0.0.1:58451 - "←[1mGET /api/teleporters HTTP/1.1←[0m" ←[32m200 OK←[0m
  1. observe developer console output on browser
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
    at ProtectedPage (http://localhost:3000/static/js/bundle.js:3006:80)
    at WithAuthenticationRequired (http://localhost:3000/static/js/bundle.js:8611:14)
1 Like

This is super useful! Thanks! I’ll investigate this with my QA team.

2 Likes

I can reproduce this issue with all of the Hello World API code samples :eyes: I’ll investigate further. Thanks for pointing it out! I’ll create a report on this and share it with the SDK Team :+1:

2 Likes

@dan-auth0 Thanks for your hard work on this. The original article (on which we’re commenting) didn’t use TypeScript. Do you anticipate putting together a code sample for React Router 6 and JavaScript?

1 Like

You are welcome, Charlie! Yes. We are working on it as we speak. :muscle: The page should be live tomorrow. I’ll share the link here.

1 Like

Sweet! Thanks for confirming I am not losing it on this end :slight_smile: . Looking forward to the patch in upstream as my current workaround is pretty ugly :smiley:

Thanks again for your efforts on the guide – coming into React with close to 0 knowledge it really helped jumpstart my project.

@dan-auth0 ,

I was successfully able to follow these instructions and upgrade our app to React 17.0.2, React-Router V6, etc.

A few things I noted about the process.

  1. This second sentence in this blurb reads funny, and I had to re-read it a few times. Maybe break that sentence up to improve readability.

  2. As other commenters have pointed out, the original documentation was written without Typescript. While I was able to figure it out with the help of @o.o post, I think this highlights that there are two audiences,

  • New Auth0 users who are starting fresh with this article.

  • Current Auth0 developers upgrading old React projects. This article is a bit lacking for these users.

I’m not sure if a completely new article is required, but I see a need to help users through the upgrade process.

My Upgrade Journey:
I ran into the following “gotchas” while upgrading our project to React-Router to V6. I don’t think all of these need to be included in an Auth0 article, but someone may run into a similar problem so I’ll log them here. Referencing this documentation is a must: https://reactrouter.com/docs/en/v6/upgrading/v5

  1. Nested Routes
    Nested routes function differently in React-Router V6, users will need to pay special attention to their syntax while writing any nested routes.

New Method
image

Old Method
image

  1. useParams replaces props.match.params
    This was a nasty one. I think useParams was released in V5.1, but our project was still using props.match.params before this update. Uses will need to import useParams with react-router-dom and update any props.match.params with the new syntax. This post was helpful: reactjs - How to pass params into link using React router v6? - Stack Overflow

Import useParams
image

Old Example:
image

New Example:
image

3. Replace useHistory with useNavigate https://reacttraining.com/blog/react-router-v6-pre/
@o.o posts provides great examples of where to do that in Auth0 related components.

4. Remove Link components (use Navigate instead): https://reactrouter.com/docs/en/v6/upgrading/v5#remove-link-component-prop
Not Auth0 React SDK specific, but I found this caused the most amount of issues in our app given how often we used the Link component.

Example of old (commented out) vs new navigation:
image

Another example (same js file):
image

image

image

image

Another example from a different file:
image

1 Like

Thanks for this feedback. We were discussing earlier this afternoon about how to better structure React content. I can share the following plan with y’all:

  • A new Developer Guide will replace the Complete Guide. It will match the style and UX of the new Developer Hub site.
    • This guide would use JavaScript, React Router v5 and I think React v17. I think it’s worth to upgrade React.
  • A new Developer Guide to migrate a project that uses Auth0 from React Router v5 to React Router v6
    • This guide would use JavaScript and React v17.
  • A new Developer Guide that shows how to migrate a JavaScript project that uses Auth0 into a TypeScript project.
    • This would use React Router v7

I don’t think that we need directly a TypeScript guide for now as there is a TypeScript code sample to use as reference as someone follows the JavaScript Authentication guide. Also, the migration guide to TS would help fill any gaps.

The Hello World React apps are simple so I am not sure if we’ll get to explore all those features of React Router in general. However, :eyes: I have plans to build and publish more complex examples to showcase features such as Auth0 Organizations, Auth0 Actions, and Fine-Grained Authorization. I think those more complex samples will allow us to show developers how Auth0 integrates with their tools to solve more intricate problems faster. :+1:

What do you think? :smiley:

4 Likes

It cool to be here…
I need a guideline on fingerprint & barometric integration on web. Am on a reactJS project where I need to enroll user’s registration data with their barometric (Via any External Fingerprint device) … have search through the internet but am yet to get a direct solution that works smooth with JavaScript or reactJS.
Ff Auth0 can solve this what are the steps I need to take to integrate it?
Thanks.

Apologies if I missed the link. Where will I find the latest update for upgrading from React Router 5?

I’ll be working on that material this quarter. There’s an issue that @o.o spotted that I have been researching and documenting. :microscope: I’ll be sharing that report with the Auth0 SDK Team :muscle:

On the meantime, I published this code sample for the JavaScript version: React Router 6 Code Sample: Basic Authentication

1 Like

Howdy, welcome to the Auth0 Community! What do you mean by “barometric integration”, please?

I followed the complete tutorial but once i click the login button nothing is happening, in console I am getting the following error

Error handling response: TypeError: Cannot read properties of undefined (reading ‘activeNetwork’)

1 Like

Howdy, Jyotirmoy! Welcome and thanks for following the tutorial.

Can you please clone this repo and checkout the add-authentication branch?

GitHub - auth0-blog/auth0-react-sample at add-authentication. Please follow the instructions on the README to set up the application. This would help us troubleshoot if the error is coming from the code or the Auth0 configuration, please.

Thanks a Million its working now !!

Can anyone check this and let me know why this ode is not working for Auth0

What do the typical timelines look like for this type of patch for the SDK team out of curiosity – would love to delete out my ugly code that gets around the issue :).

Should I just be keeping an eye on this branch: https://github.com/auth0/auth0-react/blob/react-router-v6/src/with-authentication-required.tsx ?

Also, thanks for getting out the JS Version of the doc!

1 Like

@dan-auth0 do you have any insight on that?

No specific timelines :pray: I am still exhausting some paths and pattern to submit a report to that team. On the meantime, if you’d like, you can also open an issue under the React SDK repo or comment on an existing one that addresses this concern.

2 Likes

Opened Issue 335 (React Router 6 : when using with-authentication-required, double component mount experienced due to RR6 Bug · Issue #335 · auth0/auth0-react · GitHub) for tracking.

Thanks!

1 Like