Next.js Discord

Discord Forum

Fetch data from server component using URL search query parameters

Answered
Plummer Terrier posted this in #help-forum
Open in Discord
Plummer TerrierOP
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>
  );
}

3 Replies

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
Answer