HANDLING AUTH IN REACT APPS USING NANOSTORES AND CONTEXT API
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( <form onSubmit={handleSubmit}> <div> <input name="email" onChange={(e) => setEmail(e.target.value)}/> <input name="password" onChange={(e) => setPassword(e.target.value)}/> </div> <div> <button type="submit"> Login </button> </div> </form> ) }
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} /> </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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
