How to retrieve the parameter value in Next.js version 13

I need assistance with extracting the parameter value from a GET endpoint:

/api/image/id

The directory structure is as follows:

src/app/api/image/[id]/route.ts

However, when attempting to access the id parameter, I am receiving a result of null.

import { NextRequest, NextResponse } from "next/server";

export async function GET(request: NextRequest) {
  const id = request.nextUrl.searchParams.get("id");
  return NextResponse.json({ id }, { status: 200 }); // { "id": null }

I suspect that the issue may be related to the folder structure. Unfortunately, I have been unable to determine the correct folder setup for this.

Your assistance on this matter is greatly appreciated!

I have attempted renaming route.ts to [id].ts and relocating it inside the image folder without success.

Answer №1

In the latest version of Next.js (13.2+), developers are now able to access parameters through the second parameter of the GET request.

import { NextRequest, NextResponse } from "next/server";

                                                // ⬇️ Here is the `params` property
export async function GET(request: NextRequest, { params }: { params: { id: string } } ) {

  return NextResponse.json({ id: params.id }, { status: 200 });

}

Previously, I attempted to retrieve parameters from the request object without success. It's possible that this may change in future updates as it is still an early version.

Answer №2

If you need to extract data from a URL, consider using the additional parameter available in the router handler known as context (documentation).

Imagine your URL is:

https://example.com/api/users/1

You can retrieve the value of its parameter by referencing context.params.userId. Here's an example demonstrating this concept:

export async function GET(request, context) {
  const userId = context.params.userId; // '1'
}

This code has been verified with the following setup:

// package.json
{
  "next": "13.2.4"
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Today is a day for coming together, not for waiting long periods of

When grouping by month and dealing with different days, I encountered an issue similar to the one shown in this image. https://i.stack.imgur.com/HwwC5.png This is a snapshot of my demo code available on stackblitz app.component.html <div *ngFor="let ...

create an endless loop to animate in angular2

Is there a way to add iterations, or something similar to the ccs3 animation-iteration-count in Angular 2 animations? I've looked but can't find anything related. How can we apply an infinite play to the animation? Where should we include that o ...

Designing fixed routes with several restricted parameters

I am currently working on a small project and I am unsure if it is feasible to achieve the following functionality as described below. My dynamic routes are set up like '/[community]/[townName]'. How can I create static paths where [townName] is ...

The error message "No current user" occurs when using Next JS and AWS Amplify with the getServerSideProps function

Encountering a "No current user" error while attempting to make an API call from getServerSideProps in an AWS Amplify+ NextJs project. The API is a REST API protected with AWS Cognito authentication. export async function getServerSideProps({req}) { cons ...

Creating a popup trigger in ReactJS to activate when the browser tab is closed

I am currently working on an enrollment form that requires customer information. If a user fills out half of the form and then attempts to close the tab, I want to trigger a popup giving them the option to save and exit or simply exit. While I have a jQue ...

The value 'var(--header-position)' cannot be assigned to type 'Position or undefined'

Description of Issue I am attempting to utilize a CSS Custom Property to customize a component within a nextjs application using TypeScript. Strangely, all CSS properties accept the CSS variables except for the position property which triggers the error b ...

Creating a TypeScript mixin with a partial class is a useful technique that allows you to

I am attempting to have class A inherit properties from class B without using the extends keyword. To achieve this, I am utilizing a mixin in the following manner: class A{ someProp: String someMethod(){} } class B implements classA{ someProp: String ...

Navigate to a different directory within Cypress by utilizing the cy.exec() function

Dealing with cypress to execute a python script in another directory. However, it seems like the directory change is not functioning as expected. visitPythonProject() { cy.exec("cd /Users/**/Desktop/project/"); cy.exec("ls"); // thi ...

Utilizing Next.js wildcard routes for intricate nested design

Currently, I am attempting to set up a route like /page/news/title/tab along with the corresponding folder structure. However, I encountered an error stating: "You cannot define a route with the same specificity as an optional catch-all route." Can anyon ...

Prevent updating components when modifying state variables

Introduction I've developed a React component that consists of two nested components. One is a chart (created with react-charts) and the other is a basic input field. Initially, I have set the input field to be hidden, but it becomes visible when the ...

When refreshing a page in Next.js, the loading indicator does not properly turn off

I'm currently working on my portfolio using next.js and I have implemented a 'loading' state to prevent displaying partially loaded gallery images. The 'loading' state should turn off (set to 0) once all the photos are fully loaded ...

Webpack 4.1.1 -> The configuration.module contains a property 'loaders' that is unrecognized

After updating my webpack to version 4.1.1, I encountered an error when trying to run it: The configuration object is invalid. Webpack has been initialized with a configuration that does not match the API schema. - The 'loaders' property in ...

I'm encountering a 404 error on Next.js localhost:3000

Embarking on a fresh project in Next.js, my folder structure looks like this: https://i.stack.imgur.com/HhiJo.png However, upon navigating to localhost:3000, I am greeted with a 404 error screen. It seems there is an issue with the routing, but unfortuna ...

I'm looking to locate the API documentation for AngularJS TypeScript

After transitioning from using AngularJS 1.4 and plain JavaScript to now working with AngularJS 1.5 but utilizing TypeScript, I have found it challenging to find helpful documentation. For instance, when trying to inject services like $q or $timeout into m ...

The default value in an Ionic select dropdown remains hidden until it is clicked for the first time

Having an issue with my ion-select in Ionic version 6. I have successfully pre-selected a value when the page loads, but it doesn't show up in the UI until after clicking the select (as shown in pic 2). I'm loading the data in the ionViewWillEnt ...

Using JavaScript to assign function arguments based on arbitrary object values

I am facing a challenge with a collection of arbitrary functions and a method that takes a function name along with an object or array of parameters to call the respective function. The issue arises from the varying number of inputs in these functions, som ...

Encountering Compilation Issues Post Upgrading to Angular 9

I recently upgraded my Angular application from version 8 to version 9, following the official guide. However, after the upgrade, I encountered errors that prevent my application from building. The specific errors include: "Module not found: Error: Can ...

React's useState hook is not correctly updating the state variables when the form is submitted

const [user, setuser] = useState({ name: '', lastName: '', pass: '', mail: '', uName: '' }) const [nameError, setNameError] = useState(''); const [lastNameError, setLastNameError] = useState( ...

Is there a way to utilize NextRequest and NextResponse to handle and redirect a POST request to an external API?

I'm facing some challenges with sending a post request because the server-side of my Next.js app is not parsing any data from the body. I suspect that there might be an issue with how I am accessing the server-side API. My approach involves using Nex ...

I am having trouble with my quiz function as it only checks the answer correctly for the first question. Does anyone have suggestions on how to make it work for

Currently, I'm tackling a quiz project that was assigned to me during my bootcamp. My focus right now is on the checkAnswer function, which evaluates the answer selected by the player. const startButton = document.querySelector(".start") as ...