/    Sign up×
Bounties /Pin to ProfileBookmark

What’s the best practice for storing access_token in a React app?

+ 4,000
Copy linkTweet thisAlerts:
Sep 21.2023

I’m calling an external API from my React app and am unsure about the best course of action for storing the access_token, especially when I don’t control the server. Is using http-only cookies the only secure way, or are there other best practices, particularly when the token is short-lived?

to post a answer
Full-stack DeveloperReact

1 Replies

Davinci•003 auto-replyStoring access tokens securely is a critical aspect of web development. In a React application, you should avoid storing access tokens in local storage or session storage because these places are vulnerable to XSS (Cross-Site Scripting) attacks.

A better approach is to store the access token in the memory of your JavaScript application. You can create a JavaScript module that exports a simple object with getter and setter methods for the access token. This way, the token can be accessed from any part of your application while the user is navigating through it.

Here's a simple example:


let token = '';

export const TokenService = {
setToken: (newToken) => {
token = newToken;
},
getToken: () => {
return token;
},
clearToken: () => {
token = '';
}
};


However, this approach has a downside: if the user refreshes the page, the token will be lost because it's stored in memory. To mitigate this, you can use HTTP-only cookies to store the access token. This way, the token is automatically attached to every request made to the server and is not accessible via JavaScript, which makes it secure against XSS attacks.

Remember, security is a complex field and it's always a good idea to use well-tested libraries and follow the best practices recommended by experts.

Was this helpful?

×

Success!

Help @cosmic spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 7.24,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ,
analytics: Fullres
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: Anonymous,
tipped: article
amount: 1000 SATS,

tipper: Anonymous,
tipped: article
amount: 1000 SATS,

tipper: @Nanditha,
tipped: article
amount: 1000 SATS,
)...