Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reading cookies leads to unexpected behaviour as they are sometimes 'undefined' #3176

Open
adnanbrq opened this issue Jan 15, 2025 · 1 comment

Comments

@adnanbrq
Copy link

adnanbrq commented Jan 15, 2025

Which project does this relate to?

Start

Describe the bug

I've written multiple Server Functions and I've created a helping function that reads a cookie from the given request / event.
The problem is that the cookie is sometimes there and sometimes it is not. (Dev and Prod mode)

I'm not sure if this is a more likely a Vinxi / H3 or Start bug.
To access the cookies I use getEvent offered by vinxi/http and getCookie also offered by vinxi/http.

Setting a Cookie works as expected btw.

Your Example Website or App

Steps to Reproduce the Bug or Issue

  1. Create a Helper function like this:
import { getCookie, getEvent } from "vinxi/http";
import { Optional } from "typescript-optional";
import { redirect } from "@tanstack/react-router";

export type UserSession = {}

export const requireSession = async (location?: string) => {
  const session = await getUserSession();

  if (session.isEmpty()) {
    console.log("Empty session");
    throw redirect({ to: "/auth", search: { redirect: location } });
  }

  return session.get();
};

export const getUserSession = async (): Promise<Optional<UserSession>> => {
  const event = getEvent();
  const cookie = getCookie(event, process.env.CookieKey);

  console.log("cookie: ", cookie);

  return !cookie
    ? Optional.empty()
    : Optional.ofNonNull(
        await container.SessionEncryption.Decrypt<UserSession>(cookie)
      );
};
  1. Create a Server Function Middleware like this:
export const fnAuthMiddleware = createMiddleware().server(async ({ next }) => {
  const session = await requireSession();
  return next({ context: { session } });
});
  1. Create a Server Function to check if a user is Authenticated like this example here:
export const getIsAuthenticated = createServerFn({ method: "GET" }).handler(
  async () => {
    const session = await getUserSession();
    return session.isPresent();
  }
);
  1. Now use that Server Function to restrict the access:
// routes/_authed.tsx

import { createFileRoute, Outlet, redirect } from '@tanstack/react-router';
import { getIsAuthenticated } from '../backend/session-fn';

export const Route = createFileRoute('/_authed')({
  component: RouteComponent,
  beforeLoad: async () => {
    const isAuthtenticated = await getIsAuthenticated();

    if (!isAuthtenticated) {
      throw redirect({ to: '/auth' });
    }

    return;
  },
});

function RouteComponent() {
  return <Outlet />;
}

Logs

cookie: undefined
cookie: undefined
cookie: ABC123ABC123...
cookie: undefined

Expected behavior

I would expect the Application to let me access certain parts of the UI because a valid session is given in the form of a cookie but the server cannot correctly extract that token out of a users request / event object.

Screenshots or Videos

No response

Platform

  • OS: macOS
  • Browser: Arc, Brave, Chrome, ...
  • Versions:
    • start: 1.97.0
    • react-router: 1.97.0
    • vinxi: 0.5.1

Additional context

No response

@SeanCassiere
Copy link
Member

Possibly related to #3173

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Status: No status
Development

No branches or pull requests

2 participants