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

middleware based auth for pages, robots.txt, sitemap.xml #164

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 1 addition & 6 deletions apps/web/app/(auth)/signin/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,10 @@ import { Google } from "@repo/ui/components/icons";
import gradientStyle from "./_components/TextGradient/gradient.module.css";
import { cn } from "@repo/ui/lib/utils";
import { redirect } from "next/navigation";
import { toast } from "sonner";

export const runtime = "edge";

async function Signin({
searchParams,
}: {
searchParams: Record<string, string>;
}) {
async function Signin() {
const user = await auth();

if (user) {
Expand Down
9 changes: 1 addition & 8 deletions apps/web/app/(canvas)/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,19 +1,12 @@
import { auth } from "@/server/auth";
import "./canvasStyles.css";
import { redirect } from "next/navigation";
import BackgroundPlus from "../(landing)/GridPatterns/PlusGrid";
import BackgroundPlus from "@/app/(landing)/GridPatterns/PlusGrid";
import { Toaster } from "@repo/ui/shadcn/sonner";

export default async function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
const info = await auth();

if (!info) {
return redirect("/signin");
}
return (
<>
<div className="relative flex justify-center z-40 pointer-events-none">
Expand Down
10 changes: 4 additions & 6 deletions apps/web/app/(dash)/(memories)/content.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"use client";

import { Content, StoredSpace } from "@/server/db/schema";
import { MemoriesIcon, NextIcon, SearchIcon, UrlIcon } from "@repo/ui/icons";
import type { Content, StoredSpace } from "@/server/db/schema";
import { MemoriesIcon, NextIcon, UrlIcon } from "@repo/ui/icons";
import {
ArrowLeftIcon,
MenuIcon,
Expand All @@ -12,17 +12,15 @@ import {
} from "lucide-react";
import Image from "next/image";
import Link from "next/link";
import React, { useEffect, useMemo, useState } from "react";
import React, { useMemo, useState } from "react";
import Masonry from "react-layout-masonry";
import { getRawTweet } from "@repo/shared-types/utils";
import { MyTweet } from "../../../components/twitter/render-tweet";
import { MyTweet } from "@/components/twitter/render-tweet";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuPortal,
DropdownMenuSeparator,
DropdownMenuSub,
DropdownMenuSubContent,
DropdownMenuSubTrigger,
Expand Down
3 changes: 0 additions & 3 deletions apps/web/app/(dash)/(memories)/space/[spaceid]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,8 @@ import MemoriesPage from "../../content";
import { db } from "@/server/db";
import { and, eq } from "drizzle-orm";
import { spacesAccess } from "@/server/db/schema";
import { auth } from "@/server/auth";

async function Page({ params: { spaceid } }: { params: { spaceid: number } }) {
const user = await auth();

const { success, data } = await getMemoriesInsideSpace(spaceid);
if (!success ?? !data) return redirect("/home");
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment: The redirect logic in the Page function does not handle errors properly.

Solution: Change the condition to explicitly check for both success and data.

Reason For Comment: Using a nullish coalescing operator (??) in the condition might lead to unexpected behavior. It should explicitly check for both success and data.

Suggested change
if (!success ?? !data) return redirect("/home");
if (!success || !data) return redirect('/home');


Expand Down
1 change: 0 additions & 1 deletion apps/web/app/(dash)/chat/[chatid]/loading.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import React from "react";
import { chatSearchParamsCache } from "../../../../lib/searchParams";
import ChatWindow from "../chatWindow";

async function Page({
Expand Down
6 changes: 3 additions & 3 deletions apps/web/app/(dash)/dialogContentContainer.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { StoredSpace } from "@/server/db/schema";
import type { StoredSpace } from "@/server/db/schema";
import { useEffect, useMemo, useState } from "react";
import { createMemory, createSpace } from "../actions/doers";
import { createMemory, createSpace } from "@/app/actions/doers";
import ComboboxWithCreate from "@repo/ui/shadcn/combobox";
import { toast } from "sonner";
import { getSpaces } from "../actions/fetchers";
import { getSpaces } from "@/app/actions/fetchers";
import { MinusIcon, PlusCircleIcon } from "lucide-react";
import {
DialogContent,
Expand Down
4 changes: 2 additions & 2 deletions apps/web/app/(dash)/header/header.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import React from "react";
import Image from "next/image";
import Link from "next/link";
import Logo from "../../../public/logo.svg";
import Logo from "@/public/logo.svg";

import { getChatHistory } from "../../actions/fetchers";
import { getChatHistory } from "@/app/actions/fetchers";
import NewChatButton from "./newChatButton";
import AutoBreadCrumbs from "./autoBreadCrumbs";
import SignOutButton from "./signOutButton";
Expand Down
11 changes: 2 additions & 9 deletions apps/web/app/(dash)/layout.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,11 @@
import Header from "./header/header";
import Menu from "./menu";
import { redirect } from "next/navigation";
import { auth } from "../../server/auth";
import { Toaster } from "@repo/ui/shadcn/sonner";
import BackgroundPlus from "../(landing)/GridPatterns/PlusGrid";
import { getUser } from "../actions/fetchers";
import BackgroundPlus from "@/app/(landing)/GridPatterns/PlusGrid";
import { getUser } from "@/app/actions/fetchers";

async function Layout({ children }: { children: React.ReactNode }) {
const info = await auth();

if (!info) {
return redirect("/signin");
}

const user = await getUser();
const hasOnboarded = user.data?.hasOnboarded;

Expand Down
9 changes: 3 additions & 6 deletions apps/web/app/(dash)/menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import Image from "next/image";
import Link from "next/link";
import {
MemoriesIcon,
ExploreIcon,
CanvasIcon,
AddIcon,
HomeIcon as HomeIconWeb,
} from "@repo/ui/icons";
Expand All @@ -24,12 +22,11 @@ import {
import { Label } from "@repo/ui/shadcn/label";
import { Textarea } from "@repo/ui/shadcn/textarea";
import { toast } from "sonner";
import { getSpaces } from "../actions/fetchers";
import { getSpaces } from "@/app/actions/fetchers";
import { HomeIcon } from "@heroicons/react/24/solid";
import { createMemory, createSpace } from "../actions/doers";
import { createMemory, createSpace } from "@/app/actions/doers";
import ComboboxWithCreate from "@repo/ui/shadcn/combobox";
import { StoredSpace } from "@/server/db/schema";
import useMeasure from "react-use-measure";
import type { StoredSpace } from "@/server/db/schema";

function Menu() {
const [spaces, setSpaces] = useState<StoredSpace[]>([]);
Expand Down
2 changes: 1 addition & 1 deletion apps/web/app/(landing)/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export default async function Home() {
const user = await auth();

if (user) {
await redirect("/home");
redirect("/home");
}

return (
Expand Down
13 changes: 13 additions & 0 deletions apps/web/app/robots.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { type MetadataRoute } from 'next'
import { routeGroups, routeTypes } from '@/routes'

export default function robots(): MetadataRoute.Robots {
return {
rules: {
userAgent: '*',
allow: [...routeGroups.landing],
disallow: [...routeTypes.authed],
},
sitemap: 'https://supermemory.ai/sitemap.xml',
}
}
12 changes: 12 additions & 0 deletions apps/web/app/sitemap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { type MetadataRoute } from 'next'

export default function sitemap(): MetadataRoute.Sitemap {
return [
{
url: 'https://supermemory.ai/',
lastModified: new Date(),
changeFrequency: 'yearly',
priority: 1,
}
]
Comment on lines +4 to +11
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Comment: The sitemap.xml generation logic is missing URLs for authenticated pages.

Solution: Add URLs for authenticated pages to the sitemap.xml generation logic.

Reason For Comment: The current implementation only includes the root URL, which is insufficient for SEO purposes. Authenticated pages should be included in the sitemap to improve discoverability by search engines.

Suggested change
return [
{
url: 'https://supermemory.ai/',
lastModified: new Date(),
changeFrequency: 'yearly',
priority: 1,
}
]
import{type MetadataRoute}from 'next'
export default function sitemap(): MetadataRoute.Sitemap{
return[
{url: 'https://supermemory.ai/', lastModified: new Date(), changeFrequency: 'yearly', priority: 1},
{url: 'https://supermemory.ai/app/home', lastModified: new Date(), changeFrequency: 'daily', priority: 0.8},
{url: 'https://supermemory.ai/memories', lastModified: new Date(), changeFrequency: 'daily', priority: 0.8},
{url: 'https://supermemory.ai/space', lastModified: new Date(), changeFrequency: 'daily', priority: 0.8},
{url: 'https://supermemory.ai/chat', lastModified: new Date(), changeFrequency: 'daily', priority: 0.8},
{url: 'https://supermemory.ai/note', lastModified: new Date(), changeFrequency: 'daily', priority: 0.8},
{url: 'https://supermemory.ai/canvas', lastModified: new Date(), changeFrequency: 'daily', priority: 0.8},
]
}
```

}
39 changes: 25 additions & 14 deletions apps/web/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,35 @@
import { NextRequest, NextResponse } from "next/server";
import { type NextRequest, NextResponse } from "next/server";
import { auth } from "./server/auth";
import { routeTypes } from "@/routes";

const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
};

export function middleware(request: NextRequest) {
if (request.method === "OPTIONS") {
return new NextResponse(null, { headers: corsHeaders });
}
export async function middleware(request: NextRequest) {
if (request.nextUrl.pathname.startsWith("/api")) {
if (request.method === "OPTIONS") {
return new NextResponse(null, { headers: corsHeaders });
}

const response = NextResponse.next();
Object.entries(corsHeaders).forEach(([key, value]) => {
response.headers.set(key, value);
});
const response = NextResponse.next();
Object.entries(corsHeaders).forEach(([key, value]) => {
response.headers.set(key, value);
});

return response;
return response;
}
const info = await auth();
if (routeTypes.authed.some((route) => request.nextUrl.pathname.startsWith(route))) {
if (!info) {
NextResponse.redirect(new URL("/signin", request.nextUrl));
}
} else {
if (info) {
NextResponse.redirect(new URL("/home", request.nextUrl));
}
}
return NextResponse.next();
}

export const config = {
matcher: "/api/:path*",
};
12 changes: 12 additions & 0 deletions apps/web/routes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
export const routeGroups = {
auth: ["/privacy", "/signin", "/tos"],
canvas: ["/canvas"],
dash: ["/memories", "/space", "/chat", "/home", "/note"],
landing: ["/"],
other: ["/ref", "/onboarding"],
};

export const routeTypes = {
authed: [...routeGroups.canvas, ...routeGroups.dash, ...routeGroups.other],
unauthed: [...routeGroups.auth, ...routeGroups.landing],
}