The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
blog: add pagination (#41024)
Alan Danield97aeb9780ec
diff --git a/apps/www/app/api-v2/blog-posts/route.ts b/apps/www/app/api-v2/blog-posts/route.tsnew file mode 100644index 00000000000..2ac79b060e1--- /dev/null+++ b/apps/www/app/api-v2/blog-posts/route.ts@@ -0,0 +1,87 @@+import { NextRequest, NextResponse } from 'next/server'+import { getSortedPosts } from 'lib/posts'+import { getAllCMSPosts } from 'lib/get-cms-posts'++export const revalidate = 30++// Cache for combined posts to avoid re-fetching on every request+let cachedPosts: any[] | null = null+let cacheTimestamp = 0+const CACHE_TTL = 30 * 1000 // 30 seconds++async function getCombinedPosts() {+ const now = Date.now()++ // Return cached posts if still valid+ if (cachedPosts && now - cacheTimestamp < CACHE_TTL) {+ return cachedPosts+ }++ // Get static blog posts+ const staticPosts = getSortedPosts({ directory: '_blog' })++ // Get CMS posts+ const cmsPosts = await getAllCMSPosts({ limit: 100 })++ // Combine and sort by date+ const allPosts = [...staticPosts, ...cmsPosts].sort((a: any, b: any) => {+ const dateA = new Date(a.date || a.formattedDate).getTime()+ const dateB = new Date(b.date || b.formattedDate).getTime()+ return dateB - dateA+ })++ // Update cache+ cachedPosts = allPosts+ cacheTimestamp = now++ return allPosts+}++export async function GET(request: NextRequest) {+ try {+ const { searchParams } = new URL(request.url)+ const offset = parseInt(searchParams.get('offset') || '0', 10)+ const limit = parseInt(searchParams.get('limit') || '25', 10)+ const category = searchParams.get('category')+ const search = searchParams.get('q')++ let posts = await getCombinedPosts()++ // Apply category filter+ if (category && category !== 'all') {+ posts = posts.filter((post: any) => post.categories?.includes(category))+ }++ // Apply search filter+ if (search) {+ const searchLower = search.toLowerCase()+ posts = posts.filter((post: any) => {+ return (+ post.tags?.join(' ').replaceAll('-', ' ').includes(searchLower) ||+ post.title?.toLowerCase().includes(searchLower) ||+ post.author?.toLowerCase().includes(searchLower)+ )+ })+ }++ const total = posts.length+ const paginatedPosts = posts.slice(offset, offset + limit)+ const hasMore = offset + limit < total++ return NextResponse.json({+ success: true,+ posts: paginatedPosts,+ total,+ offset,+ limit,+ hasMore,+ })+ } catch (error) {+ console.error('[blog-posts] Error:', error)+ return NextResponse.json({+ success: false,+ error: 'Internal server error',+ message: error instanceof Error ? error.message : 'Unknown error',+ })+ }+}diff --git a/apps/www/app/blog/BlogClient.tsx b/apps/www/app/blog/BlogClient.tsxindex e3c9646efe0..636cefd9ed6 100644--- a/apps/www/app/blog/BlogClient.tsx+++ b/apps/www/app/blog/BlogClient.tsx@@ -1,6 +1,6 @@'use client'-import { useState } from 'react'+import { useState, useCallback } from 'react'import DefaultLayout from 'components/Layouts/Default'import BlogGridItem from 'components/Blog/BlogGridItem'import BlogListItem from 'components/Blog/BlogListItem'@@ -8,31 +8,170 @@ import BlogFilters from 'components/Blog/BlogFilters'import FeaturedThumb from 'components/Blog/FeaturedThumb'import { cn } from 'ui'import { LOCAL_STORAGE_KEYS, isBrowser } from 'common'+import { useInfiniteScrollWithFetch } from 'hooks/useInfiniteScroll'import type PostTypes from 'types/post'export type BlogView = 'list' | 'grid'-export default function BlogClient(props: { blogs: any[] }) {+const POSTS_PER_PAGE = 25+const SKELETON_COUNT = 6++function BlogListItemSkeleton() {+ return (+ <div className="flex flex-col lg:grid lg:grid-cols-10 xl:grid-cols-12 w-full py-2 sm:py-4 h-full border-b">+ <div className="flex w-full lg:col-span-8 xl:col-span-8">+ <div className="h-6 bg-foreground-muted/20 rounded animate-pulse w-3/4" />+ </div>+ <div className="lg:col-span-2 xl:col-span-4 flex justify-start items-center lg:grid grid-cols-2 xl:grid-cols-3 gap-2 text-sm mt-2 lg:mt-0">+ <div className="hidden lg:flex items-center -space-x-2">+ <div className="w-6 h-6 rounded-full bg-foreground-muted/20 animate-pulse" />+ <div className="w-6 h-6 rounded-full bg-foreground-muted/20 animate-pulse" />+ </div>+ <div className="hidden xl:block">+ <div className="h-5 w-16 bg-foreground-muted/20 rounded-full animate-pulse" />+ </div>+ <div className="flex-1 lg:text-right">+ <div className="h-4 w-24 bg-foreground-muted/20 rounded animate-pulse ml-auto" />+ </div>+ </div>+ </div>+ )+}++function BlogGridItemSkeleton() {+ return (+ <div className="inline-block min-w-full p-2 sm:p-4 h-full">+ <div className="flex flex-col space-y-2">+ <div className="flex flex-col space-y-1">+ <div className="relative mb-3 w-full aspect-[2/1] lg:aspect-[5/3] overflow-hidden rounded-lg border border-default bg-foreground-muted/20 animate-pulse" />+ <div className="flex items-center space-x-1.5">+ <div className="h-4 w-24 bg-foreground-muted/20 rounded animate-pulse" />+ <div className="h-4 w-4 bg-foreground-muted/20 rounded animate-pulse" />+ <div className="h-4 w-16 bg-foreground-muted/20 rounded animate-pulse" />+ </div>+ <div className="h-6 w-3/4 bg-foreground-muted/20 rounded animate-pulse mt-1" />+ <div className="h-4 w-full bg-foreground-muted/20 rounded animate-pulse mt-1" />+ <div className="h-4 w-2/3 bg-foreground-muted/20 rounded animate-pulse" />+ </div>+ </div>+ </div>+ )+}++interface BlogClientProps {+ initialBlogs: any[]+ totalPosts: number+}++export default function BlogClient({ initialBlogs, totalPosts }: BlogClientProps) {const { BLOG_VIEW } = LOCAL_STORAGE_KEYSconst localView = isBrowser ? (localStorage?.getItem(BLOG_VIEW) as BlogView) : undefined- const [blogs, setBlogs] = useState(props.blogs)const [view, setView] = useState<BlogView>(localView ?? 'list')+ const [isFiltering, setIsFiltering] = useState(false)+ const [filterParams, setFilterParams] = useState<{ category?: string; search?: string }>({})+ const [filteredPosts, setFilteredPosts] = useState<any[] | null>(null)+ const [filteredTotal, setFilteredTotal] = useState<number | null>(null)const isList = view === 'list'+ // Determine which posts and total to use based on filter state+ const currentPosts = filteredPosts ?? initialBlogs+ const currentTotal = filteredTotal ?? totalPosts++ const fetchMorePosts = useCallback(+ async (offset: number, limit: number) => {+ const params = new URLSearchParams({+ offset: offset.toString(),+ limit: limit.toString(),+ })++ if (filterParams.category && filterParams.category !== 'all') {+ params.set('category', filterParams.category)+ }+ if (filterParams.search) {+ params.set('q', filterParams.search)+ }++ const response = await fetch(`/api-v2/blog-posts?${params}`)+ const data = await response.json()++ if (!data.success) {+ throw new Error(data.error || 'Failed to fetch posts')+ }++ return data.posts+ },+ [filterParams]+ )++ const {+ items: blogs,+ setItems: setBlogs,+ hasMore,+ isLoading,+ loadMoreRef,+ } = useInfiniteScrollWithFetch({+ initialItems: currentPosts,+ totalItems: currentTotal,+ pageSize: POSTS_PER_PAGE,+ fetchMore: fetchMorePosts,+ rootMargin: '1000px',+ })++ // Handle filter changes - fetch filtered results from API+ const handleFilterChange = useCallback(async (category?: string, search?: string) => {+ // If no filters, reset to initial state+ if ((!category || category === 'all') && !search) {+ setFilterParams({})+ setFilteredPosts(null)+ setFilteredTotal(null)+ setIsFiltering(false)+ return+ }++ setIsFiltering(true)+ setFilterParams({ category, search })++ try {+ const params = new URLSearchParams({+ offset: '0',+ limit: POSTS_PER_PAGE.toString(),+ })++ if (category && category !== 'all') {+ params.set('category', category)+ }+ if (search) {+ params.set('q', search)+ }++ const response = await fetch(`/api-v2/blog-posts?${params}`)+ const data = await response.json()++ if (data.success) {+ setFilteredPosts(data.posts)+ setFilteredTotal(data.total)+ }+ } catch (error) {+ console.error('Failed to fetch filtered posts:', error)+ } finally {+ setIsFiltering(false)+ }+ }, [])++ const featuredPost = initialBlogs[0]+return (<><DefaultLayout><h1 className="sr-only">Supabase blog</h1><div className="container relative mx-auto px-4 py-4 md:py-8 xl:py-10 sm:px-16 xl:px-20">- {props.blogs.slice(0, 1).map((blog) => (- <FeaturedThumb key={blog.slug} {...blog} />- ))}+ {featuredPost && <FeaturedThumb key={featuredPost.slug} {...featuredPost} />}</div><div className="border-default border-t"><div className="container mx-auto px-4 py-4 md:py-8 xl:py-10 sm:px-16 xl:px-20">- <BlogFilters allPosts={props.blogs} setPosts={setBlogs} view={view} setView={setView} />+ <BlogFilters onFilterChange={handleFilterChange} view={view} setView={setView} /><olclassName={cn(@@ -40,7 +179,28 @@ export default function BlogClient(props: { blogs: any[] }) {isList ? 'grid-cols-1' : 'grid-cols-12 lg:gap-4')}>- {blogs?.length ? (+ {isFiltering ? (+ // Show skeletons while filtering+ isList ? (+ Array.from({ length: SKELETON_COUNT }).map((_, idx) => (+ <div+ className="col-span-12 px-2 sm:px-4 [&_a]:last:border-none"+ key={`skeleton-list-${idx}`}+ >+ <BlogListItemSkeleton />+ </div>+ ))+ ) : (+ Array.from({ length: SKELETON_COUNT }).map((_, idx) => (+ <div+ className="col-span-12 mb-4 md:col-span-12 lg:col-span-6 xl:col-span-4 h-full"+ key={`skeleton-grid-${idx}`}+ >+ <BlogGridItemSkeleton />+ </div>+ ))+ )+ ) : blogs?.length ? (blogs?.map((blog: PostTypes, idx: number) =>isList ? (<div@@ -62,6 +222,12 @@ export default function BlogClient(props: { blogs: any[] }) {<p className="text-sm text-light col-span-full">No results</p>)}</ol>++ {hasMore && !isFiltering && (+ <div ref={loadMoreRef} className="flex justify-center py-8" aria-hidden="true">+ <div className="h-8 w-8 animate-spin rounded-full border-2 border-foreground-muted border-t-foreground" />+ </div>+ )}</div></div></DefaultLayout>diff --git a/apps/www/app/blog/page.tsx b/apps/www/app/blog/page.tsxindex 8d70cd17dc9..f4faeba9282 100644--- a/apps/www/app/blog/page.tsx+++ b/apps/www/app/blog/page.tsx@@ -16,6 +16,8 @@ export const metadata: Metadata = {},}+const INITIAL_POSTS_LIMIT = 25+export default async function BlogPage() {// Get static blog postsconst staticPostsData = getSortedPosts({ directory: '_blog', runner: '** BLOG PAGE **' })@@ -30,5 +32,9 @@ export default async function BlogPage() {return dateB - dateA})- return <BlogClient blogs={allPosts} />+ // Only send initial posts to client, rest will be loaded via API+ const initialPosts = allPosts.slice(0, INITIAL_POSTS_LIMIT)+ const totalPosts = allPosts.length++ return <BlogClient initialBlogs={initialPosts} totalPosts={totalPosts} />}diff --git a/apps/www/components/Blog/BlogFilters.tsx b/apps/www/components/Blog/BlogFilters.tsxindex 3bcbdbf3afc..8b3d71f825a 100644--- a/apps/www/components/Blog/BlogFilters.tsx+++ b/apps/www/components/Blog/BlogFilters.tsx@@ -3,9 +3,8 @@import { LOCAL_STORAGE_KEYS, useBreakpoint } from 'common'import { startCase } from 'lib/helpers'import { useSearchParams, useRouter } from 'next/navigation'-import { useEffect, useState } from 'react'+import { useEffect, useState, useCallback } from 'react'import type { BlogView } from 'app/blog/BlogClient'-import type PostTypes from 'types/post'import { AlignJustify, ChevronDown, Grid, Search, X as CloseIcon } from 'lucide-react'import {@@ -19,8 +18,7 @@ import {} from 'ui'interface Props {- allPosts: PostTypes[]- setPosts: (posts: any) => void+ onFilterChange: (category?: string, search?: string) => voidview: BlogViewsetView: (view: any) => void}@@ -33,7 +31,7 @@ interface Props {* ✅ search via category and reset q param if present*/-function BlogFilters({ allPosts, setPosts, view, setView }: Props) {+function BlogFilters({ onFilterChange, view, setView }: Props) {const { BLOG_VIEW } = LOCAL_STORAGE_KEYSconst isList = view === 'list'const [category, setCategory] = useState<string>('all')@@ -60,41 +58,47 @@ function BlogFilters({ allPosts, setPosts, view, setView }: Props) {'launch-week',]- useEffect(() => {- if (!q) {- handlePosts()- }- }, [category])+ // Debounced filter change to avoid too many API calls+ const debouncedFilterChange = useCallback(+ (() => {+ let timeoutId: NodeJS.Timeout+ return (cat: string, search: string) => {+ clearTimeout(timeoutId)+ timeoutId = setTimeout(() => {+ onFilterChange(cat, search)+ }, 300)+ }+ })(),+ [onFilterChange]+ )+ // Handle URL params on mountuseEffect(() => {if (q) {- handleSearchByText(q)- }- }, [q])-- const handleReplaceRouter = () => {- if (!searchTerm && category !== 'all' && router) {- router?.replace(`/blog?category=${category}`, { scroll: false })+ setSearchTerm(q)+ onFilterChange(category, q)+ } else if (activeCategory && activeCategory !== 'all') {+ setCategory(activeCategory)+ onFilterChange(activeCategory, '')}- }+ }, []) // Only run on mount- const handlePosts = () => {- // construct an array of blog posts- // not including the first blog post- const shiftedBlogs = [...allPosts]- shiftedBlogs.shift()+ const handleSearchByText = useCallback(+ (text: string) => {+ setSearchTerm(text)- handleReplaceRouter()+ // Update URL+ if (text.length > 0) {+ router?.replace(`/blog?q=${text}`, { scroll: false })+ } else {+ router?.replace('/blog', { scroll: false })+ }- setPosts(- category === 'all'- ? shiftedBlogs- : allPosts.filter((post: any) => {- const found = post.categories?.includes(category)- return found- })- )- }+ // Trigger filter change (debounced)+ debouncedFilterChange(category, text)+ },+ [category, router, debouncedFilterChange]+ )useEffect(() => {const onKeyDown = (e: KeyboardEvent) => {@@ -110,47 +114,31 @@ function BlogFilters({ allPosts, setPosts, view, setView }: Props) {setShowSearchInput(!isMobile)}, [isMobile])- useEffect(() => {- if (q) {- setSearchTerm(q)- }- if (activeCategory && activeCategory !== 'all') {- setCategory(activeCategory)- }- }, [activeCategory, q])-- function handleSearchByText(text: string) {- setSearchTerm(text)- searchParams?.has('q') && router?.replace('/blog', { scroll: false })- router?.replace(`/blog?q=${text}`, { scroll: false })- if (text.length < 1) router?.replace('/blog', { scroll: false })-- const matches = allPosts.filter((post: any) => {- const found =- post.tags?.join(' ').replaceAll('-', ' ').includes(text.toLowerCase()) ||- post.title?.toLowerCase().includes(text.toLowerCase()) ||- post.author?.includes(text.toLowerCase())- return found- })+ const handleSetCategory = useCallback(+ (newCategory: string) => {+ setSearchTerm('')+ setCategory(newCategory)- setPosts(matches)- }+ // Update URL+ if (newCategory === 'all') {+ router?.replace('/blog', { scroll: false })+ } else {+ router?.replace(`/blog?category=${newCategory}`, { scroll: false })+ }- const handleSetCategory = (category: string) => {- searchTerm && handlePosts()- searchTerm && setSearchTerm('')- setCategory(category)- category === 'all'- ? router?.replace('/blog', { scroll: false })- : router?.replace(`/blog?category=${category}`, {- scroll: false,- })- }+ // Trigger filter change immediately for category changes+ onFilterChange(newCategory, '')+ },+ [router, onFilterChange]+ )- const handleSearchChange = (event: any) => {- activeCategory && setCategory('all')- handleSearchByText(event.target.value)- }+ const handleSearchChange = useCallback(+ (event: any) => {+ setCategory('all')+ handleSearchByText(event.target.value)+ },+ [handleSearchByText]+ )const handleViewSelection = () => {setView((prevView: 'list' | 'grid') => {diff --git a/apps/www/components/Blog/BlogGridItem.tsx b/apps/www/components/Blog/BlogGridItem.tsxindex 1653fc5afe8..de4cac5dc91 100644--- a/apps/www/components/Blog/BlogGridItem.tsx+++ b/apps/www/components/Blog/BlogGridItem.tsx@@ -39,6 +39,7 @@ const BlogGridItem = ({ post }: Props) => {return (<Linkhref={post.path}+ prefetch={false}className="group inline-block min-w-full p-2 sm:p-4 h-full border border-transparent transition-all hover:bg-surface-200 dark:hover:bg-surface-75 rounded-xl"><div className="flex flex-col space-y-2">diff --git a/apps/www/components/Blog/BlogListItem.tsx b/apps/www/components/Blog/BlogListItem.tsxindex 165e9519bc2..deec2f87cb4 100644--- a/apps/www/components/Blog/BlogListItem.tsx+++ b/apps/www/components/Blog/BlogListItem.tsx@@ -48,6 +48,7 @@ const BlogListItem = ({ post }: Props) => {return (<Linkhref={post.path}+ prefetch={false}className="group flex flex-col lg:grid lg:grid-cols-10 xl:grid-cols-12 w-full py-2 sm:py-4 h-full border-b"><div className="flex w-full lg:col-span-8 xl:col-span-8">diff --git a/apps/www/hooks/useInfiniteScroll.ts b/apps/www/hooks/useInfiniteScroll.tsnew file mode 100644index 00000000000..7c58285a14a--- /dev/null+++ b/apps/www/hooks/useInfiniteScroll.ts@@ -0,0 +1,92 @@+'use client'++import { useEffect, useRef, useCallback, useState } from 'react'++interface UseInfiniteScrollOptions {+ /** Threshold for triggering the callback (0-1) */+ threshold?: number+ /** Root margin for the intersection observer */+ rootMargin?: string+}++interface UseInfiniteScrollWithFetchOptions<T> extends UseInfiniteScrollOptions {+ /** Initial items to display */+ initialItems: T[]+ /** Total number of items available */+ totalItems: number+ /** Number of items to fetch per page */+ pageSize: number+ /** Function to fetch more items */+ fetchMore: (offset: number, limit: number) => Promise<T[]>+}++export function useInfiniteScrollWithFetch<T>({+ initialItems,+ totalItems,+ pageSize,+ fetchMore,+ threshold = 0.1,+ rootMargin = '100px',+}: UseInfiniteScrollWithFetchOptions<T>) {+ const [items, setItems] = useState<T[]>(initialItems)+ const [currentTotal, setCurrentTotal] = useState(totalItems)+ const [isLoading, setIsLoading] = useState(false)+ const [hasMore, setHasMore] = useState(initialItems.length < totalItems)+ const loadMoreRef = useRef<HTMLDivElement>(null)+ const fetchingRef = useRef(false)++ // Reset when initial items change (e.g., filtering via server)+ useEffect(() => {+ setItems(initialItems)+ setCurrentTotal(totalItems)+ setHasMore(initialItems.length < totalItems)+ }, [initialItems, totalItems])++ const loadMore = useCallback(async () => {+ if (fetchingRef.current || !hasMore) return++ fetchingRef.current = true+ setIsLoading(true)++ try {+ const newItems = await fetchMore(items.length, pageSize)+ setItems((prev) => [...prev, ...newItems])+ // If we got fewer items than requested, we've reached the end+ setHasMore(newItems.length === pageSize)+ } catch (error) {+ console.error('Failed to load more items:', error)+ } finally {+ setIsLoading(false)+ fetchingRef.current = false+ }+ }, [items.length, pageSize, fetchMore, hasMore])++ useEffect(() => {+ const currentRef = loadMoreRef.current+ if (!currentRef || !hasMore || isLoading) return++ const observer = new IntersectionObserver(+ (entries) => {+ if (entries[0].isIntersecting && !fetchingRef.current) {+ loadMore()+ }+ },+ { threshold, rootMargin }+ )++ observer.observe(currentRef)++ return () => {+ observer.unobserve(currentRef)+ }+ }, [hasMore, isLoading, loadMore, threshold, rootMargin])++ return {+ items,+ setItems,+ hasMore,+ isLoading,+ loadMoreRef,+ totalCount: totalItems,+ }+}diff --git a/apps/www/public/rss.xml b/apps/www/public/rss.xmlindex b4818023fa5..070a20dc3d8 100644--- a/apps/www/public/rss.xml+++ b/apps/www/public/rss.xml@@ -2626,4 +2626,4 @@</item></channel>- </rss>\ No newline at end of file+ </rss>