In my beginner days of building full stack web apps with ReactJs, I found myself confused about how to handle authentication in the frontend. I mean, what should you do next after receiving your access token from the backend? How do you preserve login state?
Most beginners would assume “Oh, just store your token in state”. But I found out quickly that it wasn’t the best solution, nor is it even a solution at all because, as most experienced ReactJs developers know, state is temporary because it gets cleared out each time you refresh the page and we definitely can’t have user’s logging in every time they refresh.
Fast Forward to now that I've gained a little bit of experience in building full stack apps in react, studying a more experienced developer’s approach to authentication and replicating the process in two other applications, I’d like to give a guide on how I currently handle it. Some people may not think that it’s the best way but I've adopted it as my way for now and I'm open to learning other methods used by other developers.
STEP ONE
You’ve submitted your email and password (assuming you’re using basic email and password authentication) to the backend to kick off the authentication process. I will not be talking about how auth is handled in the backend because this article is about how to handle auth solely in the frontend. I will skip to the part where you have received a token in the HTTP response. Below is a code example of a simple login form component that submits the email and password to the server and receives the token and user info in the response. Now for the sake of simplicity, my form values are managed with state, it would be much better to use a robust library like formik for production apps.
import axios from 'axios' import { useState } from "react" export default function LoginForm() { const [email, setEmail] = useState("") const [password, setPassword] = useState("") const handleSubmit = async() => { try { const response = await axios.post("/api/auth/login", { email, password }) if (response?.status !== 200) { throw new Error("Failed login") } const token = response?.data?.token const userInfo = response?.data?.userInfo } catch (error) { throw error } } return() }
STEP TWO
Wrap your entire application, or just the parts that need access to the auth state in an Auth context provider. This is commonly done in your root App.jsx file. If you have no idea what context API is, feel free to check the Reactjs docs. The examples below show an AuthContext provider component created. It is then imported in App.jsx and used to wrap the RouterProvider returned in the App component, thereby making the auth state accessible from anywhere in the application.
import { createContext } from "react"; export const AuthContext = createContext(null) export default function AuthProvider({children}) { return( <authcontext.provider> {children} </authcontext.provider> ) }
import React from "react"; import { createBrowserRouter, RouterProvider } from "react-router-dom"; import AuthProvider from "./AuthContext"; const router = createBrowserRouter([ // your routes here ]) function App() { return( <authprovider> <routerprovider router="{router}"></routerprovider> </authprovider> ) } export default App
STEP THREE
In the auth context, you have to initialize two state variables, “isLoggedIn” and “authenticatedUser”. The first state is a boolean type which will be initially set to ‘false’ then updated to ‘true’ once login is confirmed. The second state variable is used to store the logged in user’s info such as names, email, etc. These state variables have to be included in the value for the provider returned in the context component so they can be accessible throughout the application for conditional rendering.
import { createContext, useState } from "react"; export const AuthContext = createContext(null) export default function AuthProvider({children}) { const [isLoggedIn, setIsLoggedIn] = useState(false) const [authenticatedUser, setAuthenticatedUser] = useState(null) const values = { isLoggedIn, authenticatedUser, setAuthenticatedUser } return( <authcontext.provider value="{values}"> {children} </authcontext.provider> ) }
STEP FOUR
Nanostores is a package for managing state in Javascript apps. The package provides a simple API for managing state values across multiple components by simply initializing it in a separate file and importing it in any component where you want to make use of the state or update it. But, for the purpose of storing your auth token received in the HTTP response in step one, you will be making use of nanostores/persistent. This package persists your state by storing it in localStorage, that way it doesn’t get cleared out when you refresh the page. @nanostores/react is a react specific integrations for nanostores, it makes available the useStore hook for extracting values from a nanostore state.
So now you can go ahead and:
Install the following packages: nanostores, @nanostores/persistent and @nanostores/react.
In a separate file named user.atom.js or whatever you choose to name it, initialize an ‘authToken’ store and a ‘user’ store using nanostores/persistent.
Import them into your login form component file and update the state with the token and user data received in your login response.
npm i nanostores @nanostores/persistent @nanostores/react
import { persistentMap } from '@nanostores/persistent' export const authToken = persistentMap('token', null) export const user = persistentMap('user', null)
import { authToken, user } from './user.atom' const handleSubmit = async() => { try { const response = await axios.post("/api/auth/login", { email, password }) if (response?.status !== 200) { throw new Error("Failed login") } const token = response?.data?.token const userInfo = response?.data?.userInfo authToken.set(token) user.set(userInfo) } catch (error) { throw error } }
STEP FIVE
Now, in your auth context that wraps your app, you have to make sure that the token and user states are kept updated and made available throughout your entire app. To achieve this, you have to:
Import the ‘authToken’ and ‘user’ stores.
Initialie a useEffect hook, inside of the hook, create a ‘checkLogin()’ function which will check whether the token is present in the ‘authToken’ store, if it is, run a function to check whether it’s expired. Based on your results from checking, you either redirect the user to the login page to get authenticated OR… set the ‘isLoggedIn’ state to true. Now to make sure the login state is tracked more frequently, this hook can be set to run every time the current path changes, this way, a user can get kicked out or redirected to the login page if their token expires while interacting with the app.
Initialize another useEffect hook which will contain a function for fetching the user information from the backend using the token in the authToken store every time the app is loaded or refreshed. If you receive a successful response, set the ‘isLoggedIn’ state to true and update the ‘authenticatedUser’ state and the ‘user’ store with the user info received in the response.
Below is the updated AuthProvider component file.
import { createContext, useState } from "react"; import { authToken, user } from './user.atom'; import { useStore } from "@nanostores/react"; import { useNavigate, useLocation } from "react-router-dom"; import axios from "axios"; export const AuthContext = createContext(null) export default function AuthProvider({children}) { const [isLoggedIn, setIsLoggedIn] = useState(false) const [authenticatedUser, setAuthenticatedUser] = useState(null) const token = useStore(authToken) const navigate = useNavigate() const { pathname } = useLocation() function isTokenExpired() { // verify token expiration and return true or false } // Hook to check if user is logged in useEffect(() => { async function checkLogin () { if (token) { const expiredToken = isTokenExpired(token); if (expiredToken) { // clear out expired token and user from store and navigate to login page authToken.set(null) user.set(null) setIsLoggedIn(false); navigate("/login"); return; } } }; checkLogin() }, [pathname]) // Hook to fetch current user info and update state useEffect(() => { async function fetchUser() { const response = await axios.get("/api/auth/user", { headers: { 'Authorization': `Bearer ${token}` } }) if(response?.status !== 200) { throw new Error("Failed to fetch user data") } setAuthenticatedUser(response?.data) setIsLoggedIn(true) } fetchUser() }, []) const values = { isLoggedIn, authenticatedUser, setAuthenticatedUser } return( <authcontext.provider value="{values}"> {children} </authcontext.provider> ) }
CONCLUSION
Now these two useEffect hooks created in step five are responsible for keeping your entire app’s auth state managed. Every time you do a refresh, they run to check your token in local storage, retrieve the most current user data straight from the backend and update your ‘isLoggedIn’ and ‘authenticatedUser’ state. You can use the states within any component by importing the ‘AuthContext’ and the ‘useContext’ hook from react and calling them within your component to access the values and use them for some conditional rendering.
import { useContext } from "react"; import { AuthContext } from "./AuthContext"; export default function MyLoggedInComponent() { const { isLoggedIn, authenticatedUser } = useContext(AuthContext) return( { isLoggedIn ? <p>Welcome {authenticatedUser?.name}</p> : <button>Login</button> } > ) }
Remember on logout, you have to clear the ‘authToken’ and ‘user’ store by setting them to null. You also need to set ‘isLoggedIn’ to false and ‘authenticatedUser’ to null.
Thanks for reading!
The above is the detailed content of HANDLING AUTH IN REACT APPS USING NANOSTORES AND CONTEXT API. For more information, please follow other related articles on the PHP Chinese website!

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Simple JavaScript functions are used to check if a date is valid. function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //test var

This article discusses how to use jQuery to obtain and set the inner margin and margin values of DOM elements, especially the specific locations of the outer margin and inner margins of the element. While it is possible to set the inner and outer margins of an element using CSS, getting accurate values can be tricky. // set up $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); You might think this code is

This article explores ten exceptional jQuery tabs and accordions. The key difference between tabs and accordions lies in how their content panels are displayed and hidden. Let's delve into these ten examples. Related articles: 10 jQuery Tab Plugins

Discover ten exceptional jQuery plugins to elevate your website's dynamism and visual appeal! This curated collection offers diverse functionalities, from image animation to interactive galleries. Let's explore these powerful tools: Related Posts: 1

http-console is a Node module that gives you a command-line interface for executing HTTP commands. It’s great for debugging and seeing exactly what is going on with your HTTP requests, regardless of whether they’re made against a web server, web serv

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

The following jQuery code snippet can be used to add scrollbars when the div content exceeds the container element area. (No demonstration, please copy it directly to Firebug) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

Notepad++7.3.1
Easy-to-use and free code editor

Dreamweaver Mac version
Visual web development tools
