1. /**
  2. * Sets session cookies for short-lived tasks with sanity checks.
  3. * @param {object} options - Configuration options for the session.
  4. * @param {string} options.domain - The domain for the cookies.
  5. * @param {string} options.path - The path for the cookies.
  6. * @param {number} options.expires - The expiration time in milliseconds.
  7. * @param {boolean} options.secure - Whether the cookie should be secure.
  8. * @param {boolean} options.httpOnly - Whether the cookie should be HTTPOnly.
  9. * @param {object} options.data - An object containing the cookie data.
  10. * @returns {Promise<void>}
  11. */
  12. async function setSessionCookie(options) {
  13. try {
  14. const { domain, path, expires, secure, httpOnly, data } = options;
  15. if (!domain || !path || expires <= 0) {
  16. throw new Error("Domain, path, and expires must be provided.");
  17. }
  18. const cookie = {
  19. name: 'session_id', // Example cookie name
  20. value: data.id, // Example cookie data
  21. domain: domain,
  22. path: path,
  23. expires: new Date(expires), // Convert milliseconds to Date object
  24. secure: secure,
  25. httpOnly: httpOnly,
  26. };
  27. // Sanity check: Ensure expires is a valid date
  28. if (isNaN(cookie.expires.getTime())) {
  29. throw new Error("Invalid expires value. Must be a valid date in milliseconds.");
  30. }
  31. document.cookie = `${cookie.name}=${cookie.value}; ${cookie.domain}; ${cookie.path}; ${cookie.expires}; ${cookie.secure}; ${cookie.httpOnly}`;
  32. console.log("Session cookie set successfully.");
  33. } catch (error) {
  34. console.error("Error setting session cookie:", error.message);
  35. throw error; // Re-throw the error for handling upstream
  36. }
  37. }

Add your comment