How to keep or resupply React Context in a Gatsby site

后端 未结 3 1515
小鲜肉
小鲜肉 2021-01-02 18:06

I use React Context API to store the information that a user is authenticated.

In development mode when I type in any URL that redirects to the 404 error page the con

3条回答
  •  天命终不由人
    2021-01-02 18:59

    You have 3 possibilities:

    1. web storage aka localStorage or sessionStorage (easiest, least secure)
    2. session cookies (secure, requires backend server)
    3. json web tokens (JWT) (most secure, requires backend server)

    An excellent read about background infromation is this blog on dev.to.

    1. web storage such as localStorage

    This is considered to be the least secure option secure option. Do not save personal data such as email adresses here. Never ever save sensitive information such as credit card information and such.

    This question describes how to use it:

    var testObject = { 'one': 1, 'two': 2, 'three': 3 };
    
    // Put the object into storage
    localStorage.setItem('testObject', JSON.stringify(testObject));
    
    // Retrieve the object from storage
    var retrievedObject = localStorage.getItem('testObject');
    
    console.log('retrievedObject: ', JSON.parse(retrievedObject));
    

    2. cookies or session cookies

    For Express you can use express-ession. Other web servers have similar middleware. The point is to supply the user info within a cookie as described on MDN.

    3. json web tokens

    This is similar to cookies but uses JSON web tokens. @coreyward gave an excellent answer. You can also read more in this blog post.

提交回复
热议问题