MENGENDALIKAN AUTH DALAM APPS REACT MENGGUNAKAN NANOSTORE DAN API KONTEKS

王林
Lepaskan: 2024-08-18 07:05:05
asal
799 orang telah melayarinya

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( 
setEmail(e.target.value)}/> setPassword(e.target.value)}/>
) }
Salin selepas log masuk

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(  {children}  ) }
Salin selepas log masuk
import React from "react"; import { createBrowserRouter, RouterProvider } from "react-router-dom"; import AuthProvider from "./AuthContext"; const router = createBrowserRouter([ // your routes here ]) function App() { return(    ) } export default App
Salin selepas log masuk

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(  {children}  ) }
Salin selepas log masuk

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
Salin selepas log masuk
import { persistentMap } from '@nanostores/persistent' export const authToken = persistentMap('token', null) export const user = persistentMap('user', null)
Salin selepas log masuk
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 } }
Salin selepas log masuk

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(  {children}  ) }
Salin selepas log masuk

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 ? 

Welcome {authenticatedUser?.name}

: } ) }
Salin selepas log masuk

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!

Atas ialah kandungan terperinci MENGENDALIKAN AUTH DALAM APPS REACT MENGGUNAKAN NANOSTORE DAN API KONTEKS. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!