简体   繁体   中英

How to persist jsonwebtoken on page reload after deploying react app

I have this code in my index page of my react app:

import React from 'react'
import ReactDOM from 'react-dom'
import {Provider} from 'react-redux'
import Router from './routes'
import {createStore, applyMiddleware, compose} from 'redux'
import thunk from 'redux-thunk'
import rootReducer from './rootReducer'
import setAuthorizationToken from './utils/setAuthorizationToken'
import {setCurrentUser} from './actions/loginActions'
import jwt from 'jsonwebtoken'

const store = createStore(rootReducer, compose(applyMiddleware(thunk), window.devToolsExtension ? window.devToolsExtension() : f => f))


if (localStorage.jwtToken) {
    setAuthorizationToken(localStorage.jwtToken)
    store.dispatch(setCurrentUser(jwt.decode(localStorage.jwtToken)))
}


ReactDOM.render(
    <Provider store={store}>
        <Router/>
    </Provider>, document.getElementById('root'))

The underlying idea is to use tokens as a form of authenticating client requests on the server. As such, every request from the client must have a token in the header which the server will decode and authenticate. A tutorial I followed added the code inside the 'if' statement, shown below (also in the code snippet above), to make sure even when a page is reloaded, the localstorage still persists this token:

  if (localStorage.jwtToken) {
    setAuthorizationToken(localStorage.jwtToken)
    store.dispatch(setCurrentUser(jwt.decode(localStorage.jwtToken)))
}

Running the app from a development server that create-react-app provides for you works fine. I can reload the page from any url eg '/', or '/profile', etc and the token is still available. Only when I log out is the token is deleted. The problem comes when I run npm build to create a production ready single js file, that I then reference in my html file. Reloading the browser from any other url that is not '/' throws an error that 'no token provided' (this is a custom error message from my node server that I want thrown when no token is attached to the request). Which simply means the browser deletes this token when I reload the page. How can I persist this token in production js file much reathe same way dev server does?

You might be using localStorage wrongly. Actually, to set a key on localStorage, you would do:

localStorage.setItem('jwtToken', 'my-token-here')

Then, to recover it:

localStorage.getItem('jwtToken')

Localstorage is the right option if you want to persist data even if the browser closes. Otherwise, if you want the data to get lost, you should use SessionStorage API.

Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM