Skip to content

Connect, collaborate, and grow with a community of TypeScript developers

Server side nav logic (#813)

Sean Boult71b3279e42e5
diff --git a/apps/web/src/app/[locale]/[username]/page.tsx b/apps/web/src/app/[locale]/[username]/page.tsx
index 8f95de7c..1405470e 100644
--- a/apps/web/src/app/[locale]/[username]/page.tsx
+++ b/apps/web/src/app/[locale]/[username]/page.tsx
@@ -11,13 +11,16 @@ export default function Page({ params }: Props) {
return <Profile username={params.username} />;
}
-export async function generateMetadata({ params: { username } }: Props) {
- const name = decodeURIComponent(username).substring(1);
- if (name)
+export async function generateMetadata({ params: { username: usernameFromQuery } }: Props) {
+ const [, username] = decodeURIComponent(usernameFromQuery).split('@');
+
+ if (!username) return {};
+
+ if (username)
return buildMetaForUser({
- username: name,
- title: `${name}'s profile | TypeHero`,
- description: `View the profile of ${name} on TypeHero.`,
+ username,
+ title: `${username}'s profile | TypeHero`,
+ description: `View the profile of ${username} on TypeHero.`,
});
return buildMetaForDefault({
title: 'Profile | TypeHero',
diff --git a/apps/web/src/app/layout.tsx b/apps/web/src/app/layout.tsx
index 3cdb803c..f00fdc8a 100644
--- a/apps/web/src/app/layout.tsx
+++ b/apps/web/src/app/layout.tsx
@@ -6,9 +6,10 @@ import { Inter } from 'next/font/google';
import type { Metadata } from 'next';
import { Toaster } from '@repo/ui/components/toaster';
import { Providers } from './providers';
+import { getServerAuthSession } from '@repo/auth/server';
import { buildMetaForDefault } from './metadata';
import { Navigation } from '~/components/navigation';
-import { CookieBanner } from '~/components/cookie-banner';
+import { getAllFlags } from '~/utils/feature-flags';
const inter = Inter({ subsets: ['latin'] });
@@ -16,7 +17,10 @@ export async function generateMetadata(): Promise<Metadata> {
return buildMetaForDefault({});
}
-export default function RootLayout({ children }: { children: React.ReactNode }) {
+export default async function RootLayout({ children }: { children: React.ReactNode }) {
+ const flags = await getAllFlags();
+ const session = await getServerAuthSession();
+
return (
<html suppressHydrationWarning lang="en">
<head>
@@ -32,10 +36,9 @@ export default function RootLayout({ children }: { children: React.ReactNode })
</head>
<body className={`${inter.className} flex flex-col`}>
<Providers>
- <Navigation />
+ <Navigation session={session} flags={flags} />
<main className="flex-1">{children}</main>
<Toaster />
- {/* <CookieBanner /> */}
</Providers>
<Analytics />
</body>
diff --git a/apps/web/src/components/navigation.tsx b/apps/web/src/components/navigation.tsx
index 2e70bbd0..0f5d1859 100644
--- a/apps/web/src/components/navigation.tsx
+++ b/apps/web/src/components/navigation.tsx
@@ -1,7 +1,7 @@
'use client';
-import { signIn, signOut, useSession } from '@repo/auth/react';
-import { type RoleTypes } from '@repo/db/types';
+import { signIn, signOut } from '@repo/auth/react';
+import type { Session } from '@repo/auth/server';
import { Button } from '@repo/ui/components/button';
import {
DropdownMenu,
@@ -11,15 +11,16 @@ import {
DropdownMenuTrigger,
} from '@repo/ui/components/dropdown-menu';
import { Loader2, LogIn, Moon, Play, Settings, Settings2, Sun, User } from '@repo/ui/icons';
+import type { EdgeConfigItems } from '@vercel/edge-config';
import clsx from 'clsx';
import { useTheme } from 'next-themes';
import Link from 'next/link';
import { usePathname, useRouter } from 'next/navigation';
-import { useContext, useEffect, useState } from 'react';
+import { useEffect, useState } from 'react';
import { useFullscreenSettingsStore } from '~/app/[locale]/challenge/_components/fullscreen';
-import { FeatureFlagContext } from '~/app/feature-flag-provider';
import { isAdminOrModerator } from '~/utils/auth-guards';
+// TODO: move this to a util as it might be used in other places
export function getAdminUrl() {
// reference for vercel.com
if (process.env.VERCEL_URL) {
@@ -30,18 +31,15 @@ export function getAdminUrl() {
return `http://localhost:3001`;
}
-const roleTypes: typeof RoleTypes = {
- USER: 'USER',
- ADMIN: 'ADMIN',
- MODERATOR: 'MODERATOR',
- CREATOR: 'CREATOR',
-};
-
-export function Navigation() {
+export function Navigation({
+ session,
+ flags,
+}: {
+ session: Session | null;
+ flags: EdgeConfigItems;
+}) {
const { fssettings } = useFullscreenSettingsStore();
const pathname = usePathname();
- const { data } = useSession();
- const featureFlags = useContext(FeatureFlagContext);
return (
<header className="z-0 w-full">
@@ -82,7 +80,7 @@ export function Navigation() {
hero
</span>
</Link>
- {featureFlags?.exploreButton ? (
+ {flags?.exploreButton === true && (
<Link href="/explore" className="ml-4">
<div
className={clsx('hover:text-foreground text-foreground/80 transition-colors', {
@@ -92,8 +90,8 @@ export function Navigation() {
Explore
</div>
</Link>
- ) : null}
- {featureFlags?.tracksButton ? (
+ )}
+ {flags?.tracksButton === true && (
<Link href="/tracks" className="ml-4">
<div
className={clsx('hover:text-foreground text-foreground/80 transition-colors', {
@@ -103,12 +101,12 @@ export function Navigation() {
Tracks
</div>
</Link>
- ) : null}
+ )}
</div>
<div className="flex">
<div className="flex items-center justify-end gap-2">
<ThemeButton />
- {featureFlags?.loginButton ? <LoginButton /> : null}
+ <LoginButton session={session} />
</div>
</div>
</div>
@@ -145,24 +143,21 @@ function ThemeButton() {
);
}
-function LoginButton() {
- const [loading, setLoading] = useState(false);
- const { data: session, status } = useSession();
+function LoginButton({ session }: { session: Session | null }) {
+ const [isSigningIn, setSigningIn] = useState(false);
const router = useRouter();
-
const isAdminOrMod = isAdminOrModerator(session);
- // NOTE: 1. loading == true -> 2. signIn() -> 3. session status == 'loading' (loading == false)
+ // We start the flow client side, then a full page redirect will happen
const handleSignIn = async () => {
try {
- setLoading(true);
- // page reloads after sign in, so no need to setLoading(false), othersiwe ugly visual glitch
+ setSigningIn(true);
await signIn('github', { redirect: false });
} catch (error) {
- // only set loading to false if there was an error and page didn't reload after sign in
- setLoading(false);
+ console.error(error);
}
};
+
const handleSignOut = async () => {
await signOut({ redirect: false });
router.refresh();
@@ -194,22 +189,22 @@ function LoginButton() {
<span>Settings</span>
</DropdownMenuItem>
</Link>
- {isAdminOrMod ? (
+ {Boolean(isAdminOrMod) && (
<a className="block" href={getAdminUrl()}>
<DropdownMenuItem className="focus:bg-accent rounded-lg p-2 duration-300 focus:outline-none dark:hover:bg-neutral-700/50">
<Settings className="mr-2 h-4 w-4" />
<span>Admin</span>
</DropdownMenuItem>
</a>
- ) : null}
- {isAdminOrMod ? (
+ )}
+ {Boolean(isAdminOrMod) && (
<a className="block" href="/challenge-playground">
<DropdownMenuItem className="focus:bg-accent rounded-lg p-2 duration-300 focus:outline-none dark:hover:bg-neutral-700/50">
<Play className="mr-2 h-4 w-4" />
<span>Challenge Playground</span>
</DropdownMenuItem>
</a>
- ) : null}
+ )}
<DropdownMenuSeparator />
<Button
className="h-8 w-full justify-start rounded-b-lg rounded-t-sm bg-opacity-50 px-2 text-red-500 hover:bg-red-500/20 hover:text-red-500"
@@ -222,11 +217,11 @@ function LoginButton() {
</DropdownMenu>
) : (
<Button
+ disabled={isSigningIn}
className="focus:bg-accent w-20 rounded-lg bg-transparent p-2 text-black duration-300 hover:bg-gray-200 focus:outline-none dark:text-white hover:dark:bg-gray-800"
- disabled={loading || status === 'loading'}
onClick={handleSignIn}
>
- {loading || status === 'loading' ? (
+ {isSigningIn ? (
<Loader2 className="h-5 w-5 animate-spin" />
) : (
<div className="flex items-center space-x-2">
diff --git a/tooling/config-eslint/utils/rules.js b/tooling/config-eslint/utils/rules.js
index 95ebb4e6..eb12ac79 100644
--- a/tooling/config-eslint/utils/rules.js
+++ b/tooling/config-eslint/utils/rules.js
@@ -41,7 +41,6 @@ module.exports = {
'no-control-regex': 'off',
'no-return-await': 'off',
'@typescript-eslint/require-await': 'off',
-
// Best practice/readability
// Some of these might be opinions.
// You can ignore if you'd like.