Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

docs: Add "How to Set Up React User Authentication" Post #316

Open
wants to merge 2 commits into
base: master
Choose a base branch
from

Conversation

lukiccd
Copy link
Contributor

@lukiccd lukiccd commented Dec 11, 2024

Related Issue

Link to the Github Issue created for this blog post

Link to Google Doc

TODO

Checklist

  • Has cover image been added
  • Have all content images been added. Do they render correctly? (aspect ratio etc)
  • The code inside code blocks gives no errors
  • Check for SEO keyword?
  • Added call to action to link to supertokens and to link to other blogs.
  • Add reference to how SuperTokens solves this blog's problem (if relevant).

Remaining TODOs

  • ...

Copy link

netlify bot commented Dec 11, 2024

Deploy Preview for gracious-clarke-e6b312 ready!

Name Link
🔨 Latest commit 497676f
🔍 Latest deploy log https://app.netlify.com/sites/gracious-clarke-e6b312/deploys/679815d9d15dbf0008d0252b
😎 Deploy Preview https://deploy-preview-316--gracious-clarke-e6b312.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.

To edit notification comments on pull requests, go to your Netlify site configuration.

* **Auth0** offers an easy-to-implement, scalable solution for user authentication, making it ideal for applications that need social logins and advanced features.
* **Firebase** simplifies authentication with email/password, phone, and social media providers, making it a great choice for projects already using other Firebase services.
* **SuperTokens** is perfect if you want the flexibility of self-hosting your authentication system, or using the cloud option, while still using pre-built solutions for login, session management, and secure token handling.
2. **Custom Authentication Solutions**: For projects that require full control over the authentication process, building a custom solution with **Node.js** and **Express** might be the best route. This approach allows you to design the authentication flow exactly as you need, manage sensitive user data securely, and integrate custom business logic. However, it comes with a higher development and maintenance cost compared to using a service like SuperTokens.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mention that most developers would be better suited using a service and focus their development efforts on the core business logic

---
title: How to Set Up React User Authentication
date: "2025-01-28"
description: "User authentication forms the backbone of security in modern web applications, especially within the **React** ecosystem. Ensuring that only authenticated users can access specific parts of your application is crucial for safeguarding data integrity and access control."
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Markdown does not work in the frontmatter

Suggested change
description: "User authentication forms the backbone of security in modern web applications, especially within the **React** ecosystem. Ensuring that only authenticated users can access specific parts of your application is crucial for safeguarding data integrity and access control."
description: "User authentication forms the backbone of security in modern web applications, especially within the React ecosystem. Ensuring that only authenticated users can access specific parts of your application is crucial for safeguarding data integrity and access control."

1. **Create a New React App Using Create React App**
To build a secure user login, start by setting up a new React application. Using Create React App, you can quickly initialize the project:

| bash npx create-react-app my-auth-app cd my-auth-app npm install npm start |
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use proper markdown code blocks. They will have language specific highlighting and are easier to read.

Suggested change
| bashnpx create-react-app my-auth-app cd my-auth-app npm install npm start |
```bash
�npx create-react-app my-auth-app cd my-auth-app npm install npm start

| bash npx create-react-app my-auth-app cd my-auth-app npm install npm start |
| :---- |

This command creates the basic app structure where you’ll integrate authentication with Auth0, JWTs, and Express. By setting up on `localhost:3000`, you can easily test authentication routes and calls to a backend running locally.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Give a better description of what this command is doing : creating a demo react app, installing the dependencies and starting it up


This command creates the basic app structure where you’ll integrate authentication with Auth0, JWTs, and Express. By setting up on `localhost:3000`, you can easily test authentication routes and calls to a backend running locally.

2. **Structure of the Application**
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is this being done here? We have just setup and application, there are no components/contexts/apis/uitl functions created yet. This is a little confusing and unnecessary

1. **Using** `react-router` **to Create Private Routes**
Set up route paths with `BrowserRouter` and create protected routes using constants for easier management.

| javascript import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom'; const PrivateRoute \= ({ component: Component, ...rest }) \=\> ( \<Route {...rest} render={(props) \=\> isAuthenticated ? \<Component {...props} /\> : \<Redirect to="/login" /\> } /\> ); |
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fix code snippet

1. **Clearing Tokens and Updating State**
Add a logout button that clears tokens and resets authentication state in the context.

| javascript const handleLogout \= () \=\> { localStorage.removeItem('token'); setIsAuthenticated(false); }; |
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fix code snippet

2. **Step-by-Step Guide to Setting Up SuperTokens in a React App**
To get started, check out this comprehensive [tutorial on building a login screen with React and Bootstrap](https://supertokens.com/blog/building-a-login-screen-with-react-and-bootstrap). Begin by installing the SuperTokens SDK for seamless integration:

| bash npm install supertokens-auth-react supertokens-node |
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fix code snippet


Next, configure SuperTokens in your app’s main file, such as `App.js`. This setup ensures SuperTokens handles authentication details, including secure session management, which is particularly useful for [setting up social and email-password logins in ReactJS](https://supertokens.com/blog/how-to-set-up-social-and-email-password-login-with-reactjs).

| javascript import { init } from 'supertokens-auth-react'; const appInfo \= { appName: "MyApp", apiDomain: "http://localhost:5000", websiteDomain: "http://localhost:3000", }; init({ appInfo }); |
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fix code snippet

1. **Creating User Accounts and Handling Sign-In**
SuperTokens makes it easy to implement user registration and login within your React app. By adding a simple login component, you can authenticate users securely with minimal code:

| javascript import { signIn } from 'supertokens-auth-react'; import React, { useState } from 'react'; const LoginForm \= () \=\> { const \[email, setEmail\] \= useState(''); const \[password, setPassword\] \= useState(''); const handleLogin \= async () \=\> { const response \= await signIn({ email, password }); if (response.status \=== "OK") { console.log("Login successful"); } else { console.log("Login failed"); } }; return ( \<form onSubmit={(e) \=\> { e.preventDefault(); handleLogin(); }}\> \<input type="email" value={email} onChange={(e) \=\> setEmail(e.target.value)} placeholder="Email" /\> \<input type="password" value={password} onChange={(e) \=\> setPassword(e.target.value)} placeholder="Password" /\> \<button type="submit"\>Login\</button\> \</form\> ); }; |
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

fix code snippet

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants