Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to securely store JWT tokens in react/next.js application?

I need to store JWT token which is generated when a valid user login after proper registration through REST API. I read and find these ways to store JWT in client site: local storage, session storage, cookies, HttpOnly cookie, Browser memory (React state).

Need suggestion to store JWT in the proper method and also can access some certain APIs for get with JWT token as post request header parameter user-related data.

here is my login code part where I store JWT token to window object at this point, saved previously on local storage but now need to store safely in other ways except local storage or cookies.

const handleSubmitLogin = evt => {
evt.preventDefault();
var cart = new Cart();

var request = new NFRequest();
var response = request.api(HTTP_METHOD.POST, '/auth', {
    'email_address': allValuesLogin.email_login,
    'password': allValuesLogin.password_login,
    'cart_list': cart.getCartPostData(),
});
response.then((res) => {
    if (res.type === 'success') {
        window.$token = res.data.token
        setLoginSuccess('Successfully Login')
        setTimeout(()=> {
            setLoginSuccess('');
        }, 3000)
        cart.handle({ action_type: "RESET_ITEMS" });
        Router.push('/account')
    } else {
        setLoginError('Wrong Email or Password')
        setTimeout(()=> {
            setLoginError('');
        }, 3000);
    }
});
}

here I store the JWT token:window.$token = res.data.token

Thank you.

like image 302
Mahmud Hasan Jion Avatar asked Dec 04 '25 17:12

Mahmud Hasan Jion


1 Answers

It's up to you on how to store it. Generally, this is the most to least secure:

  1. Browser memory
  2. Http-only cookie
  3. local storage
  4. session storage / cookie

The most important thing is to make sure your website is protected against XSS and CSRF attacks.

like image 163
Todd Skelton Avatar answered Dec 07 '25 07:12

Todd Skelton