Next.js Discord

Discord Forum

How to create catch all API route in app router?

Answered
Piping Plover posted this in #help-forum
Open in Discord
Piping PloverOP
With the pages router, it was possible to create a catch all API route using /pages/api/post/[...slug].ts and then you could get the URL using const { slug } = req.query.
import type { NextApiRequest, NextApiResponse } from 'next'
 
export default function handler(req: NextApiRequest, res: NextApiResponse) {
  const { slug } = req.query
  res.end(`Post: ${slug.join(', ')}`)
}

Source: https://nextjs.org/docs/pages/building-your-application/routing/api-routes#catch-all-api-routes

With the app router, how would we do the same thing?
Answered by Ray
//app/api/post/[...slug]/route.ts
import type { NextRequest, NextResponse } from 'next/server'
 
export async function GET(req: NextRequest, {params}:{ params: { slug: string[] } }) {
  const { slug } = params
  return new NextResponse(`Post: ${slug.join(', ')}`)
}
View full answer

5 Replies

Answer
@Ray ts //app/api/post/[...slug]/route.ts import type { NextRequest, NextResponse } from 'next/server' export async function GET(req: NextRequest, {params}:{ params: { slug: string[] } }) { const { slug } = params return new NextResponse(`Post: ${slug.join(', ')}`) }
Piping PloverOP
Hmm.. for some reason I'm getting a 404 error Not Found when trying to fetch the route. Any ideas why? Here's how I'm fetching it.

// app/page.tsx
  function fetchData() {
    fetch(`/api/posts/test`)
      .then((res) => console.log(res))
      .catch((error) => console.error(error));
  }
@Ray oh the file path should be `app/api/post/[...slug]/route.ts`
Piping PloverOP
Oh thanks! I forgot to have the [...slug] in the folder path