Reputation: 3339
I have this code inside getServerSideProps
which gives me the token value from a cookie named token
:
const token = context.req.cookies?.token || null;
const auth = true;
//Then I sent the token to server
const settings = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Authorization': "Bearer " + token,
},
body: JSON.stringify({ "limit": "10" })
};
The cookie is a httpOnly
cookie I receive from a post request sent with Set-Cookie
header.
The thing is, I want to use the token not only in page components (getServerSideProps
is only in page components). In other components I'd like to sometimes use functions that give me more data, let's say all the messages of the client - based on his token (I limit it to 10 in logs.js
and I want to increase it in my inner component functions) . Is it safe to pass the token via props and then use it in my functions? I have logs.js
component, which has another component named Messages
, and inside the Messages
component I want to call a function to get more messages but I am not sure whether it is safe or not because the idea of getting the token in getServerSideProps
is that nobody can see it, or am I wrong?
If I am not wrong, what is the best way to get the token from the client-side in order to send requests inside inner components?
Upvotes: 1
Views: 1285
Reputation: 5870
the idea of getting the token in getServerSideProps is that nobody can see it
Not really when it comes to cookies. Cookies will be sent to the browser so anyone can see it anyways. What you do with it in getServerSideProps
is hidden, but the cookie itself is visible.
Because it's an httpOnly cookie, you can't access it with javascript on the client. So if you need the cookie value in javascript, you have a few options:
getServersideProps
and pass that value to your page and through to your components. This will work if you only need your components to read the cookie value.{ httpOnly: false }
cookie which will allow it to be read (and written to) by javascript. I wouldn't do this if it has anything to do with security, because then anyone can not only read the cookie but could change it and do whatever they want with it.You mentioned it's a token - the big question is: what is the token for in terms of security? You mention using it to determine if you should have more than 10 logs. Is that a business requirement? Would something bad happen (like you lose money, a breach, etc?) if someone manipulated it to show 20, 30, 1,000?
If your business needs to show the user only 10 except in the case where his/her token increases that limit, and you don't want the user to manipulate the limit, leave it as httpOnly
, read it in getServerSideProps
, and then pass the number to your component. Then, nothing can be manipulated or changed because the client can't mess with the token to unlock more logs.
Upvotes: 2