request.query is undefined in Next.js 13 API route

558 Views Asked by At

Here's a simplified version of the code structure I'm using:

In app/api/events/route.js:

import Event from "@models/Event";
import { connectToMongoDB } from "@utils/database/connectToMongoDB";

export default async (req, res) => {
  console.log(req);
  const { filterBy, ...filters } = req.query;
  // Rest of the code...
}


And following is the implementation of the above endpoint in app/(root)/page.jsx:

export async function getServerSideProps() {
  const response = await fetch(`/api/events?filterBy=status&status=Live`);
  // Rest of the code...
}

I'm getting the following error:

- error TypeError: Cannot destructure property 'filterBy' of 'request.query' as it is undefined.

Here's the request object that I logged to console:

NextRequest [Request] {
  [Symbol(realm)]: {
    settingsObject: { baseUrl: undefined, origin: [Getter], policyContainer: [Object] }
  },
  [Symbol(state)]: {
    method: 'GET',
    localURLsOnly: false,
    unsafeRequest: false,
    body: null,
    client: { baseUrl: undefined, origin: [Getter], policyContainer: [Object] },
    reservedClient: null,
    replacesClientId: '',
    window: 'client',
    keepalive: false,
    serviceWorkers: 'all',
    initiator: '',
    destination: '',
    priority: null,
    origin: 'client',
    policyContainer: 'client',
    referrer: 'client',
    referrerPolicy: '',
    mode: 'cors',
    useCORSPreflightFlag: false,
    credentials: 'same-origin',
    useCredentials: false,
    cache: 'default',
    redirect: 'follow',
    integrity: '',
    cryptoGraphicsNonceMetadata: '',
    parserMetadata: '',
    reloadNavigation: false,
    historyNavigation: false,
    userActivation: false,
    taintedOrigin: false,
    redirectCount: 0,
    responseTainting: 'basic',
    preventNoCacheCacheControlHeaderModification: false,
    done: false,
    timingAllowFailed: false,
    headersList: HeadersList {
      cookies: null,
      [Symbol(headers map)]: [Map],
      [Symbol(headers map sorted)]: [Array]
    },
    urlList: [ URL {} ],
    url: URL {
      href: 'http://[::1]:3000/api/events?filterBy=status&status=Live',
      origin: 'http://[::1]:3000',
      protocol: 'http:',
      username: '',
      password: '',
      host: '[::1]:3000',
      hostname: '[::1]',
      port: '3000',
      pathname: '/api/events',
      search: '?filterBy=status&status=Live',
      searchParams: URLSearchParams { 'filterBy' => 'status', 'status' => 'Live' },
      hash: ''
    }
  },
  [Symbol(signal)]: AbortSignal { aborted: false },
  [Symbol(abortController)]: AbortController { signal: AbortSignal { aborted: false } },
  [Symbol(headers)]: HeadersList {
    cookies: null,
    [Symbol(headers map)]: Map(20) {
      'accept' => [Object],
      'accept-encoding' => [Object],
      'accept-language' => [Object],
      'cache-control' => [Object],
      'connection' => [Object],
      'cookie' => [Object],
      'host' => [Object],
      'sec-ch-ua' => [Object],
      'sec-ch-ua-mobile' => [Object],
      'sec-ch-ua-platform' => [Object],
      'sec-fetch-dest' => [Object],
      'sec-fetch-mode' => [Object],
      'sec-fetch-site' => [Object],
      'sec-fetch-user' => [Object],
      'upgrade-insecure-requests' => [Object],
      'user-agent' => [Object],
      'x-invoke-output' => [Object],
      'x-invoke-path' => [Object],
      'x-invoke-query' => [Object],
      'x-middleware-invoke' => [Object]
    },
    [Symbol(headers map sorted)]: [
      [Array], [Array], [Array],
      [Array], [Array], [Array],
      [Array], [Array], [Array],
      [Array], [Array], [Array],
      [Array], [Array], [Array],
      [Array], [Array], [Array],
      [Array], [Array]
    ]
  },
  [Symbol(internal request)]: {
    cookies: RequestCookies { _parsed: [Map], _headers: [HeadersList] },
    geo: {},
    ip: undefined,
    nextUrl: NextURL { [Symbol(NextURLInternal)]: [Object] },
    url: 'http://localhost:3000/api/events?filterBy=status&status=Live'
  }
}

I'm encountering the issue in my Next.js application when passing query parameters to the API route. I'm using getServerSideProps in a Next.js page component and fetching data from an API route, but it seems that the query parameters are not being correctly received on the server side.

I tried using useEffect instead of getServerSideProps and the issue still persists.

1

There are 1 best solutions below

2
On

First of all the signature of your route handler is wrong and it can even work at all within the app router because you are trying to apply the same logic that was used in the pages router.

Route handlers must be a named export such as GET, POST etc. Additionally here's a snippet of a fully working route handler accessing URL search params:

import { type NextRequest } from 'next/server'
 
export function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams
  const query = searchParams.get('query')
  // query is "hello" for /api/search?query=hello
}

This is all assuming you actually use the app router as implied by your paths starting with /app.