How To Use Cookies
Sometimes our frontends need to hold a bit of data like for user authentication. It can be useful to store an access token in the frontend and send it along with requests to authenticate the current user. Let’s explore how this pattern would work in a Pageous project.
Let’s say you have a mutation called “Login Mutation”.
Feel free to create this mutation now in a test project if you want to follow along.
This mutation will hit the /login
endpoint of your service.
This hypothetical endpoint takes a username and password and responds with:
{ "token": "my-secret-access-token" }
Navigate to “Login Mutation” and scroll down to “Set Cookies”. You’ll see three input fields:
Cookie name: The name of your cookie, this can be anything permetted by HTTP.
We can just use tokenCookie
here.
GJSON: This is a GJSON string.
It will be used on the response data to extract the value of the cookie.
To extract the token
value from the response with a GJSON string all we need to put here is token
.
Max age seconds: Is the amount of time before the cookie will expire in seconds. Set to 1209600
for 2 weeks.
Click “Update Mutation”. You’ll see your cookie listed now.
Go edit the service that this login mutation is for. Specifically you now want to edit the REST headers. Add the following to the REST headers:
{{#params.cookies.tokenCookie}}
Authorization: Bearer {{params.cookies.tokenCookie}}
{{/params.cookies.tokenCookie}}
This will conditionally add the Authorization
header to all requests to the service if tokenCookie is set.