Retrieving URL parameters within an API route handler in Next.js

Within my client component called GetUserInfoButton, I initiate a GET request using the URL format of

http://localhost:3000/test/users/[id]
. The [id] in this URL is represented by an alphanumeric sequence similar to MongoDb.

My intention within the file app/api/users/[id]/route.ts is to handle and process this incoming request with the corresponding [id]. Below is the code snippet for my GetUserInfoButton component:

'use client';

export default function GetUserInfoButton({ id }: { id: string }) {
    const contentType = "application/json";
    const handleClick = async (id: string) => {
        try {
            const res = await fetch(`/api/users/${id}`, {
                method: "GET",
                headers: {
                    "Content-Type": contentType,
                }
            });
            if (!res.ok) {
                throw new Error(res.status.toString());
            }
        } catch (error) {
            console.log("error ===> ", error);
        }
    };

    return (
        <button onClick={() => handleClick(id)}>
            Get
        </button>
    );
}

Furthermore, here is the content of my route.ts file:

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

export async function GET(req: NextRequest) {
    const id = req.url.split("http://localhost:3000/api/users/")[1];
    return NextResponse.json({
        success: true,
        id: id
    }, {
        status: 200,
    })
}

In the past when utilizing the pages router, I could employ useRouter() on the client-side to access the id. Now, in the server component context, how can I obtain the id parameter?

It's worth noting that my project is built using Next.js version 13.4.16.

Answer №1

When navigating inside the app directory, specifically in a dynamic route within the [id] folders, your API route handler will receive a second object parameter containing the slug, as detailed in the documentation:

// app/api/users/[id]/route.ts

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

export async function GET(req: NextRequest, { params }: { params: { id: string } }) {
  console.log(params.id);
  return NextResponse.json({ msg: "Hello World" });
}

Below is the version of the code snippet without types:

// app/api/users/[id]/route.js

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

export async function GET(req, { params }) {
  console.log(params.id);
  return NextResponse.json({ msg: "Hello World" });
}

For those reading this in the future, you can access query strings (e.g., ?search=value) using the following method:

import { NextResponse } from "next/server";

export async function GET(req) {
  const { searchParams } = new URL(req.url);
  console.log(searchParams.get("search"));
  return NextResponse.json({ msg: "Hello World" });
}

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

Managing HTML5 Video in a slider

I've designed a unique video slider that cycles through 4 videos. Each video has a custom play button and additional overlay content. Once the video starts playing, the overlay content and play button fade out to reveal the default video controls. The ...

Having difficulty retrieving text data from a web URL using JavaScript

I am trying to extract text data from a web URL () My approach involved using two node modules. 1) Using crawler-Request it('Read Pdf Data using crawler',function(){ const crawler = require('crawler-request'); functio ...

Utilizing Vue.js 2.x to send a REST API request with a collection of objects

I currently have an array of objects stored in state, and my goal is to send this entire structure to a back end API for processing and receive a new set of values in return. Below is a simplified representation of this structure as viewed in the develope ...

Creating dynamic variable names in Jquery by combining strings and numbers

Hey there, I'm really stuck and in need of a solution for the issue I've encountered. Currently, I have a script that sends an Ajax GET request and retrieves JSON data. The data is successfully returned, but when I try to loop through it, that&a ...

JavaScript problem with setting values in 2D array

I am attempting to assign values to a 2d array at particular indices. During each iteration, all sub-arrays at the j index are being assigned the same variable (number). inputTensor dimensions: 140x7 - 140 arrays of size 7 inputMinArray dimensions: 1x7 - ...

Identifying text within a paragraph using JavaScript regex, excluding any URLs mentioned

How can I use JavaScript on the client side to find a search term in a paragraph while excluding any matches that are part of a URL? I attempted to use the following regex but encountered an error: "A quantifier inside a lookbehind makes it non-fixed widt ...

stopping action when hovering

Looking for some assistance with my javascript function that scrolls through an array of images on a set interval. I want to enhance it by pausing the rotation when hovering over any of the images. Javascript (function() { var rotator = document.getE ...

Users are reporting that verification emails are not being sent when the Accounts.createUser function is used within

I have a simple meteor method set up to create user accounts. In my server/methods.js file: Meteor.methods({ createUserAccount: function(user) { return Accounts.createUser(user); } }); Then in my server/init.js file: Meteor.startup(function() ...

Avoid excessive clicking on a button that initiates an ajax request to prevent spamming

When using two buttons to adjust the quantity of a product and update the price on a digital receipt via ajax, there is an issue when users spam the buttons. The quantity displayed in the input box does not always match what appears on the receipt. For in ...

What is the most efficient way to retrieve the operating system's name and version using JavaScript?

I'm in the process of developing an object that will simplify accessing browser and system information by implementing a function. One particular function within this object is responsible for retrieving the operating system name and version, returnin ...

"Modifying state within a child component and utilizing the refreshed value in the parent component

I'm currently working on creating a simple header mini cart with a cart item counter in NextJS. I'm utilizing the form state value in the header component and then passing that value to the child components of the header where the numerical quant ...

Update the current value in array.prototype

Recently, I've noticed that the built-in JavaScript sort function can be unreliable at times. To address this issue, I decided to create my own sorting function. Consider the following scenario: Array.prototype.customSort = function(sortFunction, upd ...

Steps on how to set the values of a select option based on a JSON parsed array

After receiving an array from a JSON call, I am trying to populate a select element with the data. {1:Android, 2:IOS, 3:Business Management Systems, 4:Database, 5:Codes/Scripts, 6:Others} or 1: "Android" 2: "IOS" 3: "Business Management Systems" 4: "Da ...

Executing a function after an AngularJS directive's reference function has been called

<CustomDirective customValue="someValue" anotherFunctionRef="anotherFunction()"></CustomDirective> angular.module('AppName', ['OtherDependencies']). directive('CustomDirective', ...

Establish the default sorting for Material UI tables

I'm struggling with setting the default sorting for a Material UI table. Is there a more straightforward way to do this without using a button at the top? I want the table to automatically sort by protein when it is loaded. import * as React from &apo ...

Leveraging Object.assign for updating fields in Firebase documents

Currently, I am working on a website that allows users to create new projects by filling out a form with all the necessary project information. Within this form, there is a file input field where users can upload images and documents. I have successfully i ...

Struggling to maintain context with axios in React despite diligent use of arrow functions

In my component, I have a function for posting data. Although it works well, the context of my component is lost in the success message. This is puzzling because I am using arrow functions. Why does the "this" context get lost in this situation? The issu ...

Event response lacks necessary latlng data from Gmaps API

Currently, I am utilizing Angular UI Google Maps and facing an issue in retrieving the latlng when a map click event occurs. Although the map is responding, it is not providing the latlng information as expected. Below is the excerpt of my code: Controlle ...

Utilizing JavaScript for enhancing the appearance of code within a pre element

Is there a way to dynamically highlight the code inside a pre element using vanilla JavaScript instead of JQuery? I'm looking for a solution that colors each tag-open and tag-close differently, displays tag values in another color, and attributes with ...

@keyframes shimmering-fade

I'm attempting to create a text animation effect (please see video) but I'm struggling to find the solution!! Can someone assist me with this? Should I use JavaScript for a better result? h1.fadeinone { animation: fadeinone 10s;} h1.fadeintwo ...