Skip to content

OpenPanel is an open-source web and product analytics platform, an open-source alternative to Mixpanel with optional self-hosting.

1.6 KB
Raw Blame
import { createRouter as createTanstackRouter } from '@tanstack/react-router';
import { setupRouterSsrQueryIntegration } from '@tanstack/react-router-ssr-query';
import { CompassIcon } from 'lucide-react';
import * as TanstackQuery from './integrations/tanstack-query/root-provider';
import { routeTree } from './routeTree.gen';
import { getServerEnvs } from './server/get-envs';
import { EmptyState } from '@/components/empty-state';
import { LinkButton } from '@/components/ui/button';

export const getRouter = async () => {
  const envs = await getServerEnvs();
  const rqContext = TanstackQuery.getContext(envs.apiUrl);

  const router = createTanstackRouter({
    scrollRestoration: true,
    routeTree,
    context: {
      ...rqContext,
      ...envs,
      session: {
        session: null,
        user: null,
        userId: null,
      },
    },
    defaultPreload: 'intent',
    defaultNotFoundComponent: () => (
      <EmptyState
        description="The page you're looking for doesn't exist or has moved."
        icon={CompassIcon}
        title="Page not found"
        variant="page"
      >
        <LinkButton href="/">Go to home</LinkButton>
      </EmptyState>
    ),
    Wrap: (props: { children: React.ReactNode }) => {
      return (
        <TanstackQuery.Provider {...rqContext} apiUrl={envs.apiUrl}>
          {props.children}
        </TanstackQuery.Provider>
      );
    },
  });

  setupRouterSsrQueryIntegration({
    router,
    queryClient: rqContext.queryClient,
  });

  return router;
};

declare module '@tanstack/react-router' {
  interface Register {
    router: ReturnType<typeof getRouter>;
  }
}