#Use script variable in html
1 messages · Page 1 of 1 (latest)
In Astro, you can use the Astro.cookies API to read and write cookies. This API provides a Map-like interface for handling cookies. You can use it to get the authToken from the cookies. Here's how you can do it:
---
// Import your jwt_decode library
import jwt_decode from "jwt-decode";
// Get the authToken from the cookies
const authToken = Astro.cookies.get("authToken").value;
// Decode the authToken
const decode: { id: string } = jwt_decode(authToken);
console.log(decode);
---
In this code, Astro.cookies.get("authToken").value is used to get the authToken from the cookies. Then, jwt_decode(authToken) is used to decode the authToken.
Please note that this code should be placed in the frontmatter script of your Astro component (between the --- lines at the top of the file).
Also, remember to handle the case where the authToken might not exist or be invalid. You can use Astro.redirect to redirect the user to a login page if the authToken is not valid.
For more information, you can refer to the Astro.cookies documentation (https://docs.astro.build/en/reference/api-reference/#astrocookies) and the Astro.redirect documentation (https://docs.astro.build/en/reference/api-reference#astroredirect).
Please note that the jwt_decode library is not mentioned in the provided extracts, so make sure to import and use it correctly in your project.
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
@quartz cargo kapa.ai is still learning and improving, please let us know how it did by reacting below
@patent raven it's not reading the cookie. I believe because its inside --- and not being ran on the browser?
Let me check the knowledge base for you. One moment! :books:
Yes, you're correct. The code inside the --- (frontmatter) in Astro runs on the server-side, not in the browser. This means it doesn't have access to browser-specific APIs like cookies.
If you need to access cookies, you should do so within a <script> tag in the HTML part of your Astro component. This code will be sent to the browser and executed there. However, please note that the Astro.cookies API is not available in the browser.
Here's an example of how you can use a <script> tag to run JavaScript in the browser:
<script>
// Your JavaScript code here
</script>
Remember, any console.log() statements or other debug output within a <script> tag will be printed to the console in your browser, as mentioned in the Astro documentation (https://docs.astro.build/en/guides/troubleshooting#js-scripts).
If you need to use server-side data in the browser, you can pass it from the server-side script to the client-side script using props in your Astro component. However, this might not be applicable for sensitive data like authentication tokens.