Implement authentication without library
Unanswered
Birman posted this in #help-forum
BirmanOP
I am trying to implement auth using JWT token with React Context. Here is an example of what I have so far
The redirect works and after login, I am redirected to
// This stores the access token in context - src/context/AuthContext.tsx
"use client";
import ...
interface User { token: string }
export const AuthContext = createContext<[User, React.Dispatch<React.SetStateAction<User>>] | null>(null);
export const AuthContextProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [user, setUser] = useState<User>(null!);
return <AuthContext.Provider value={[ user, setUser ]}>{children}</AuthContext.Provider>
};
export const useAuthContext = () => {
const context = useContext(AuthContext);
return context;
};// Login page - src/app/login.tsx
export default function Page() {
const router = useRouter();
const [_, setUser] = useAuthContext();
async function handleFormSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
const formData = new FormData(e.currentTarget);
const res = await postLoginForm(formData);
const data = await res.json();
if (data.success == true) {
setUser({ token: data.data.accessToken });
router.push("/");
}
}
return <form onSubmit={handleFormSubmit}>
<input name="email" />
<input name="password" />
<button type="submit">Submit</button>
</form>
}// This checks token - src/components/CheckAuth.tsx
"use client";
import ...
export default function CheckAuth({ children }: { children: React.ReactNode }) {
const [user] = useAuthContext();
const router = useRouter();
if (!user) return router.push("/login")
return <div>{children}</div>
}// Protected page - src/app/page.tsx
import CheckAuth from "@/components/CheckAuth";
export default function Home() {
return <CheckAuth><div>Homepage</div></CheckAuth>
}The redirect works and after login, I am redirected to
/ but when I refresh / page, it goes back to /login. What am I doing wrong? Thanks for reading.3 Replies
react context wont persist on refreshes
what you do for auth is, make sure the jwt has only public data like the user id, username etc.. and then yeet it into local storage or even better cookies
and when you need to auth, decode the jwt.. get the public data and use thoseto get data from the server