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

Leveraging weather application programming interfaces

I am trying to set up a basic webpage that can display tide information from wunderground.com. However, for some reason I am not seeing any results on the page. I have included the load function in hopes of at least getting something to appear when the p ...

Utilizing @casl/vue in conjunction with pinia: A guide to integrating these

I'm currently facing an issue with integrating @casl/ability and Vue 3 with Pinia. I'm unsure of how to make it work seamlessly. Here is a snippet from my app.js: import { createApp } from "vue" const app = createApp({}) // pinetree i ...

Creating dynamic rows for Firebase data in React BootstrapTable can be accomplished by dynamically rendering each row

Hey everyone, I'm currently working on a web app project where I am creating a table. Below is the code snippet for it: class Table1 extends Component { render() { return ( <div> <BootstrapTable data={this.props.data}> ...

Saving MongoDB query results to a file using the built-in Node.js driver

I have been attempting to save the output of a MongoDB query to a file using the native Node.js driver. Below is my code (which I found on this post: Writing files in Node.js): var query = require('./queries.js'); var fs = require('fs' ...

Tips for retrieving the return value from a function with an error handling callback

I am having an issue with my function that is supposed to return data or throw an error from a JSON web token custom function. The problem I am facing is that the data returned from the signer part of the function is not being assigned to the token const a ...

Looking to streamline your webpack configuration in vue.config.js? Utilize webpack-chain for efficient setup. And, wondering how to leverage the speed-measure-webpack

Below is the setup in my vue-cli3 configuration file: vue.config.js: const path = require('path') const CompressionWebpackPlugin = require('compression-webpack-plugin') const SpeedMeasurePlugin = require("speed-measure-webpack-plugin" ...

Assist with JavaScript Programming

Can someone assist me in creating functionality for the "Show Picture" button to toggle the visibility of the picture when clicked? I've been trying to achieve this using an If/Else statement for a school project but have been struggling with it. Any ...

Developed a verification process using Discord.JS, however, I'm not receiving any feedback when trying to configure the command

As I embark on creating my debut Discord bot to enhance my coding skills, I have encountered numerous hurdles along the way. While most of these challenges were overcome by me independently, this particular issue has left me stumped. The objective of the ...

Controller experiencing peculiar AJAX response in CodeIgniter

I recently embarked on a Codeigniter project and now I'm faced with the task of making an AJAX call to a specific controller. Here is the scenario: - I have two dropdown menus: one for selecting counties and the other should populate with cities with ...

Is the accuracy of the in-situ convolution filter guaranteed?

After analyzing my simple box blur function, I have come to the realization that it may be incorrect. The current implementation edits the ImageData object in place, leading to convolution filters depending on surrounding pixels that have already been ch ...

The read more button is not functioning properly when used in conjunction with the <br>

Can someone help me debug an issue I'm facing with my code? I have created an HTML tab that contains multiple DOM elements, each with a "Read More" button. Everything works fine when it's just plain text, but as soon as I add tags within the p ...

Dividing a sentence by spaces to isolate individual words

Recently, I encountered a challenging question that has me stuck. I am working on creating an HTML text box where the submitted text is processed by a function to check for any links. If a link is detected, it should be wrapped in anchor tags to make it cl ...

Regular Expression: locate the occurrence of "//" followed by any character other than a space

I am looking to add a space by replacing the target with the code "// ". That's all you need to know from the title. My attempts so far have looked like this: \/\/\b(?! ) However, this approach does not catch strings like "//$..." ...

Adjust the dimensions of input tag depending on the length of content in Angular

Is there a way to dynamically set the size of the input tag in my HTML based on the length of the ng-model value? I attempted this approach: <span>Node Path: <input for="nodeName" type="text" ng-model="nodePath" size="{{nodePath.length()}}"ng- ...

VueJS: What is the easiest way to create a new instance of a div with just a click of a button?

Is there a way to create a function that will generate a new instance of a specific div (.container in the template) when a button (#addDiv) is clicked, with the button being the only visible element on the webpage initially? I have heard about using docum ...

How can a child value be transferred from a client component to a parent component on the server side?

I am facing a situation where a client-side component needs to send a value to its parent component which is server-side. I have tried using useState and other hooks, but so far it has been unsuccessful. Can anyone provide guidance on how to achieve this? ...

Encountering a reference error while attempting to troubleshoot streamline.js generated JavaScript code

After successfully setting up streamline.js and generating code using _node --standalone -c stest._js, I encountered an issue. The generated code was not readable and debugging it in tools like Chrome's developer console seemed impossible. However, I ...

The project is not being recognized by 'webpack' when running within it

Every time I attempt to execute 'webpack' in my project, the command line shows me this error message: 'webpack' is not recognized as an internal or external command, operable program or batch file. I have installed webpack using th ...

What could be the reason for Next.js throwing the error message "Unhandled Runtime Error: Rendered more hooks than during the previous render."?

I recently encountered an issue with the client component in my Next.js application that tracks the time spent within the app. Below is the code snippet I am using for this purpose: 'use client'; import React, { useEffect, useState } from ' ...

How to reset a form in AngularJS using either HTML or a built-in directive

Within a standard modal popup in Bootstrap, I have implemented a form consisting of input fields, a submit button, a cancel button, and a close-icon. When selecting the name from an Object data-list using ng-repeat, the popup containing the form will displ ...