I have created service to communicate with my backend for user registration and login. I use the JS fetch API and send all data through HTTPS. I use JWT tokens to authenticate queries once I have logged, and this is stored in the window local storage.
The API details are stored in a config.json file.
Two things that I'm not sure if I can improve are:
- Should I use local storage for storing the JWT token or is there a better alternative?
- Is it ok to send the password without hashing it first on the client side? On the server side it is hashed and salted before storage so no plaintext passwords are stored.
import config from "../config.json"
let jwtToken = null;
const login = async (email, pass) => {
const loginData = {
"email": email,
"password": pass
}
const loginResponse = await fetch(config.host + config.loginUrl, {
body: JSON.stringify(loginData),
method: "POST",
headers: {
'Content-Type': 'application/json'
}
})
if(loginResponse.ok)
{
jwtToken = await loginResponse.text();
window.localStorage.setItem("jwtToken", jwtToken);
return true;
}
return false;
}
const register = async ({ firstName,
lastName,
email,
password
}) => {
const registrationData = {
"firstName":firstName,
"lastName":lastName,
"email": email,
"password":password
};
const registerResponse = await fetch(config.host + config.usersUrl, {
body: JSON.stringify(registrationData),
method: "POST",
headers: {
'Content-Type': 'application/json'
}
})
return registerResponse.ok;
}
const logout = () =>
{
window.localStorage.removeItem("jwtToken", null);
}
const isLoggedIn = () => !(window.localStorage.getItem("jwtToken") === null);
const userSerivce = {
login,
logout,
register,
isLoggedIn
}
export default userSerivce;
```