Cookie-based session management helps websites remember who you are by storing small data pieces in your browser. This way, you stay logged in or keep your preferences while browsing.
Cookie-based session management in Astro
import { getCookies, setCookie } from 'astro:cookies'; // To set a cookie const cookieHeader = setCookie('sessionId', 'abc123', { path: '/', httpOnly: true, maxAge: 3600 }); // response.headers.append('Set-Cookie', cookieHeader); // To get cookies const cookies = getCookies(); const sessionId = cookies.get('sessionId');
setCookie returns a 'Set-Cookie' header string with options like httpOnly to keep it safe from JavaScript access and maxAge to set expiration time. Append it to response headers.
getCookies reads all cookies sent by the browser in the current request and returns a Map.
user with value Alice that lasts for one day.setCookie('user', 'Alice', { path: '/', maxAge: 86400 });
user cookie.const cookies = getCookies();
console.log(cookies.get('user'));setCookie('sessionId', 'xyz789', { path: '/', httpOnly: true, secure: true });
This Astro server endpoint checks if a sessionId cookie exists. If not, it creates a new session ID, sets it as a cookie, and returns it in the response. This keeps track of the user session using cookies.
import { getCookies, setCookie } from 'astro:cookies'; export async function GET({ request }) { const cookies = getCookies(request.headers); let sessionId = cookies.get('sessionId'); const headers = new Headers({ 'Content-Type': 'text/plain' }); if (!sessionId) { sessionId = 'sess_' + Math.random().toString(36).slice(2); const cookieHeader = setCookie('sessionId', sessionId, { path: '/', httpOnly: true, maxAge: 3600 }); headers.append('Set-Cookie', cookieHeader); } return new Response(`Your session ID is: ${sessionId}`, { headers }); }
Cookies set with httpOnly cannot be read by JavaScript, which improves security.
Always set the path option to control where the cookie is sent.
Use maxAge or expires to control how long the cookie lasts.
Cookies store small data in the browser to remember user sessions.
Astro provides setCookie and getCookies to manage cookies easily.
Secure cookies help protect session data from being stolen by scripts.
Practice
Solution
Step 1: Understand what cookies do
Cookies store small data on the user's browser to keep track of information like sessions.Step 2: Identify the role in session management
Cookies help remember who the user is between page visits by storing session IDs or tokens.Final Answer:
To store small pieces of data in the browser to remember user sessions -> Option BQuick Check:
Cookies = store session data [OK]
- Thinking cookies speed up server code
- Confusing cookies with styling tools
- Believing cookies increase webpage size
sessionId with value abc123 in Astro?Solution
Step 1: Check function usage
Astro'ssetCookietakes the cookie name as a string and the value as a string.Step 2: Validate syntax correctness
setCookie('sessionId', 'abc123') correctly passes both arguments as strings, matching the expected syntax.Final Answer:
setCookie('sessionId', 'abc123') -> Option AQuick Check:
Correct string arguments = setCookie('sessionId', 'abc123') [OK]
- Omitting quotes around value
- Using variable without quotes for name
- Using assignment syntax inside function call
import { setCookie, getCookies } from 'astro:cookies';
export async function get({ request }) {
const cookies = getCookies(request);
if (!cookies.user) {
return new Response('No user cookie', { status: 401 });
}
setCookie('lastVisit', new Date().toISOString());
return new Response(`Welcome back, ${cookies.user}!`);
}What will be the response if the request has a cookie
user=Alice?Solution
Step 1: Check cookie presence
The code gets cookies from request and checks ifcookies.userexists. Withuser=Alice, it passes the check.Step 2: Identify the error in setCookie
setCookie('lastVisit', new Date().toISOString())lacks the required first Response argument, causing a runtime error before returning the greeting.Final Answer:
Error: setCookie requires response object -> Option AQuick Check:
setCookie(response, name, value) [OK]
- Overlooking incorrect setCookie usage
- Assuming greeting returns despite error
- Misreading cookie presence logic
import { setCookie } from 'astro:cookies';
export async function post({ request }) {
setCookie('session', 'xyz', { secure: true });
return new Response('Session set');
}Solution
Step 1: Understand setCookie usage
In Astro, to set a cookie on the response, you must attach it to the response headers, not just call setCookie alone.Step 2: Identify missing response handling
The code calls setCookie but does not attach the cookie to the response, so the cookie won't be sent.Final Answer:
setCookie must be called with the response object to attach cookie -> Option DQuick Check:
Cookie needs response headers [OK]
- Calling setCookie without response context
- Thinking secure option is unsupported
- Forgetting to return response with cookie
Solution
Step 1: Check expiration setting
To expire in 1 hour, usemaxAge: 3600(seconds). One option uses it correctly with secure: true; another uses incorrect expires value.Step 2: Verify secure and httpOnly flags
Secure must be true to send only over HTTPS. HttpOnly helps protect cookie from scripts.Step 3: Compare options
Options with secure: false or incorrect expires fail. The snippet with maxAge: 3600, secure: true, httpOnly: true satisfies expiration, HTTPS-only, and adds security.Final Answer:
setCookie('sessionId', 'abc123', { maxAge: 3600, secure: true, httpOnly: true }) -> Option CQuick Check:
Expire 1hr + secure + httpOnly = setCookie('sessionId', 'abc123', { maxAge: 3600, secure: true, httpOnly: true }) [OK]
- Using expires with wrong Date format
- Setting secure to false for HTTPS-only cookie
- Forgetting httpOnly for security
Ready to prove it?
Pass the test and this pattern moves unknown
