Use Cookies

Learn how to read, write, and delete cookies from both API routes and React components.

Overview

Cookies are a fundamental way to store small amounts of data (like session IDs, user preferences, or language settings) in the user's browser.

In JopiJS, you can manage cookies from:

  • API Routes (onGET, onPOST, etc.): Pure server-side management.
  • React Components (page.tsx): Isomorphic management (works on both server and client).

In this guide, you will learn how to:

  • Create, read, and delete cookies.
  • Manage cookie expiration and security options.
  • Handle cookies in isomorphic React components.

1. Cookies in API Routes (Server-Side)

When building APIs, you often need to set cookies for authentication or tracking. JopiJS provides a clean interface via the JopiRequest object.

src/mod_api/@routes/login/onPOST.ts
import { JopiRequest } from "jopijs";

export default async function(req: JopiRequest) {
    // 1. Read a cookie from the request
    const currentLang = req.cookie_getReqCookie("lang") || "en-us";

    // 2. Set a new cookie in the response
    //
    // Note: it's for the sample here since
    // JopiJS manage himself the sessions.
    //
    req.cookie_addCookieToRes("session_id", "abc-123", { 
        maxAge: 60 * 60 * 24 * 7 // 7 days
    });

    // 3. Delete a cookie
    if (shouldLogout) {
        req.cookie_deleteResCookie("session_id");
    }

    return req.res_jsonResponse({ success: true });
}

2. Cookies in React Components

JopiJS offers hooks and utilities to manage cookies directly within your UI. These utilities are isomorphic, meaning they work during Server-Side Rendering (SSR) and after hydration in the browser.

Using useStaticEffect

useStaticEffect is like useEffect, but it is also executed server side.
It's why it is recommended to manage cookies within a useStaticEffect.

src/mod_theme/@routes/page.tsx
import { getCookieValue, setCookie, deleteCookie, useStaticEffect } from "jopijs/ui";
import { useState } from "react";

export default function MyPage() {
    const [theme, setTheme] = useState("light");

    useStaticEffect(() => {
        // 1. Read cookie (Server or Browser)
        const savedTheme = getCookieValue("theme");
        if (savedTheme) setTheme(savedTheme);

        // 2. Set cookie
        setCookie("last_visit", new Date().toISOString(), { maxAge: 86400 });
    }, []);

    const toggleTheme = () => {
        const nextTheme = theme === "light" ? "dark" : "light";
        setTheme(nextTheme);
        setCookie("theme", nextTheme);
    };

    return (
        <button onClick={toggleTheme}>Current Theme: {theme}</button>
    );
}

Important for Pages:
Isomorphic cookie management only works effectively if the page is not fully static/cached. If your page uses autoCache.enable, the server-side part of useStaticEffect will only run once during build/first-hit.


Summary of Methods

Server (JopiRequest)

  • req.cookie_getReqCookie(name)
  • req.cookie_addCookieToRes(name, value, options)
  • req.cookie_deleteResCookie(name)

UI (jopijs/ui)

  • getCookieValue(name)
  • setCookie(name, value, options)
  • deleteCookie(name)