#How to store/access cookies

6 messages · Page 1 of 1 (latest)

ocean bison
#

I'm using an external api which redirects the user to the following page after logging in:
http://localhost:5173/redirect?token={JWT token}
The JWT is added by the external api.

I managed to store the JWT in a cookie with the following route:

// routes/redirect.tsx
import { useSearchParams, createCookieSessionStorage } from "solid-start";
import { createServerData$, redirect } from "solid-start/server";

export const storage = createCookieSessionStorage({
  cookie: {
    name: "token",
    httpOnly: true,
    sameSite: "lax",
    path: "/",
    maxAge: 60 * 60 * 24 * 14,
    secure: true,
  },
});

export default function routeData() {
  return createServerData$(async () => {
    const [query] = useSearchParams<{token: string}>();
    const session = await storage.getSession();
    session.set("token", query.token);
    return redirect("/profile", {
      headers: {
        "Set-Cookie": await storage.commitSession(session),
      },
    });
  });
}

as described here: https://start.solidjs.com/advanced/session
To me it does not seem like the correct solution for my case because the session is already stored on the external api server. (now also on my server?)
What is the correct way of storing this cookie (or any cookie) and how do I access the cookie on a page?

vapid cipher
#

I think it makes sense to store the cookie in the session in your case. JWT can be store anywhere but having it in a session makes it accessible by the server whereas localstorage would be client only.

#

Once you've stored and commited the session, you will be able to use const session = await storage.getSession(request) on the server-side to get the session and the use session.get('token') to retrieve the token

#

Small note: I'm not sure if you put your createCookieSessionStorage in routes/redirect.tsx or if it was to share a short snippet of code but you should rather put it in a separate file (like src/session.ts for example) to be able to import it between different routes

ocean bison
#

I think you're right but to me it seemed unnecessary. (my thinking probably makes my problem unnecessarily complicated)

So when the user routes to a page, does the routeData have access to the server state? My understanding of SSR is that only the initial page load is SSR and the following are done client side?
If so, do I access the request as follows?

export default function routeData() {
  return createServerData$(async (_, event) => {
    const request = event.request;
    ...
  });
}
sturdy oriole
#

yeah then you use routeData inside your component as a signal