enter image description hereI have a mongo DB server which an API set up when you input a proper username and password it sends a JWT access token in the body of the response as shown in the picture it works. (takes an email and password to verify)
I’m building a front-end application now to post an authentication request which is working fine, However what i want to do is store the body of the response in a cookie with a key of x-auth-toekn to be sent in the body of all api requests. Chat gpt spit this out which says it saves the response in a cookie however in dev tools application tab i see nothing saved.
front end code is as follows and i’m receiving the api payload’s response but it’s not being stored. I want to be able to reuse the token (will figure out refresh tokens later fyi)
import React, { useState } from "react";
const LoginForm: React.FC = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [token, setToken] = useState<string | null>(null);
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
try {
const response = await fetch("https://myapi.com/api/auth", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, password }),
});
if (!response.ok) {
throw new Error("Failed to login");
}
const jsonResponse = await response.json();
const authToken = jsonResponse["x-auth-token"];
if (authToken) {
// Save token in cookie
document.cookie = `authToken=${authToken}; path=/`;
// Alternatively, save token in local storage
// localStorage.setItem('authToken', authToken);
setToken(authToken);
console.log("Token:", authToken);
} else {
throw new Error("Token not found in response");
}
} catch (error) {
console.error("Login Error:", error.message);
}
};
return (
<div>
<h2>Login Form</h2>
{token ? (
<p>Logged in! Token: {token}</p>
) : (
<form onSubmit={handleSubmit}>
<div>
<label htmlFor="email">Email:</label>
<input
type="email"
id="email"
name="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
required
/>
</div>
<div>
<label htmlFor="password">Password:</label>
<input
type="password"
id="password"
name="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
required
/>
</div>
<button type="submit">Login</button>
</form>
)}
</div>
);
};
export default LoginForm;
Picture showing the JWT is arriving from my API in the body of the response, i assume it’s json but it has no parenthesis in the response.
Hunter C is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.