Create Cookie Session

    0

    3

    Jose Romero

    Remix TypeScript public recipes

    The code first checks to see if sessionSecret is set (it is not). If it is not, an error is thrown. The key to understanding this code is the creation of the three functions: getSession, commitSession, and destroySession.

    getSession takes an optional CookieOptions object as its only parameter and returns a Cookie object. The Cookie object has the following properties:

    name: The name of the cookie. This is the name that will be displayed to the user when they create or edit the cookie.

    domain: The domain that the cookie will be set for. This can be either the domain of the website that the user is on, or the domain of the server that the cookie is being stored on.

    expiry: The expiration date of the cookie.

    httpOnly: Whether the cookie should be accessible only by the user who sets it, or by other users who have been given permissions to access cookies.

    maxAge: The maximum age of the cookie, in minutes.

    path: The path on the web server where the cookie will be stored.

    sameSite: Whether the cookie will be set to be same-site or cross-site. SameSite cookies will be stored

    Library: remix

    Shortcut: remix.cookie.session

    import { createCookieSessionStorage } from "remix";
    
    const sessionSecret = process.env.SESSION_SECRET;
    if (!sessionSecret) {
      throw new Error("SESSION_SECRET must be set");
    }
    const { getSession, commitSession, destroySession } =
      createCookieSessionStorage({
        // a Cookie from `createCookie` or the CookieOptions to create one
        cookie: {
          name: "__session",
          // all of these are optional
          domain: "domain.tld",
          expires: new Date(Date.now() + 60),
          httpOnly: true,
          maxAge: 60,
          path: "/",
          sameSite: "lax",
          secrets: [sessionSecret],
          secure: true
        }
      });
    export { getSession, commitSession, destroySession };
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    Legal
    • Security
    • Privacy Policy
    • Code Privacy
    • Terms of Service
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.