#Fetch data from server component using URL search query parameters

5 messages · Page 1 of 1 (latest)

proven pawn
#

I've been struggling with this pattern and can't find a good example in the docs.

I'm using Next.js 14 and the App Directory structure so getStaticProps is out of the question. I want to read the URL query params and pull out certain vars to control state, for example /news?page=2.

From what I can tell Next Request is what I'm looking for, but it doesn't seem to work when running next build, but does work when running next dev

import BlogPost from "@/components/blog-post/BlogPost";
import ContentfulApi from "@/src/contentful/contentfulClient";
import { NextRequest } from "next/server";


export default async function News(request: NextRequest) {
  const page = parseInt(request.searchParams.page || "0", 10) || 1;
  const posts = await ContentfulApi.getBlogPosts(page, 10);

  return (
    <div>
      <h1>News</h1>
      {posts.map((post: any) => (
        <BlogPost key={post.sys.id} post={post} />
      ))}
    </div>
  );
}
left whaleBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

jaunty trail
#
export default function Page({
  params,
  searchParams,
}: {
  params: { slug: string }
  searchParams: { [key: string]: string | string[] | undefined }
}) {
  return <h1>My Page</h1>
}
#

the server component receive the object above and not request object