Passing multiple parameters in URL for APIs using Next.js

Is there a way to pass multiple parameters and retrieve results from the next.js API?

I found the documentation very helpful, you can check it out here

/api/posts/[postId].js

The above setup works fine, but I want to know if it's possible to pass another parameter as shown below:

/api/posts/[postId][userId].js

The current folder name is [postId], and I attempted to rename it to [postId][userId]

This is the snippet of code I have for the API:

  let postVotes = await req.db.collection('votesPosts').count({"post":req.query.postId,"user":req.query.userId})

Answer №1

Typically, routes are not designed to handle multiple parameters within a single segment of the URL path. Each segment should only contain one parameter:

/api/entity/{param1}/{param2}/sub/{param3}

In Next JS, you must also separate them in order to have 2 segments with parameters:

/api/posts/[postId]/[userId]

This structure would correspond to two possible files:

/api/posts/postId]/[userId]/index.js

If you use a parameter directory along with an index file, or

/api/posts/postId]/[userId].js

If you opt for a parameter file.

Using a directory along with an index file allows you to include fixed segments like:

/api/posts/postId]/[userId]/popular.js
/api/posts/postId]/[userId]/private.js

This approach enables you to make API calls similar to when dealing with 2 parameters.

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

I am looking to adjust/modulate my x-axis labels in c3 js

(I'm specifically using c3.js, but I also added d3.js tags) I have been working on creating a graph that displays data for each month based on user clicks. However, I am facing an issue where the x-axis labels show 0-X instead of 1-X. For instance, ...

Encountering an issue with the v-carousel component from Vuetify: receiving a 'Cannot read property 't' of undefined' error message

Currently, I am trying to create an image carousel using Laravel along with Vue/Vuetify. The issue lies in the fact that the Vuetify v-carousel and v-carousel-item components are not rendering properly due to the error mentioned in the title. I have alrea ...

nodejs express routing issue resulting in not found error

I recently started a new node project and wanted to enhance my route adding capabilities. In the past, I only went one level deep with folders, but this time I wanted to go further. To achieve this, I created a recursive function that adds routes and navig ...

Changing the Style of a CSS Module Using JavaScript

Embarking on a journey into Javascript and React, I am currently working on my first React app. My aim is to adjust the number of "gridTemplateRows" displayed on the screen using a variable that will be updated based on data. Right now, it's hardcode ...

Is it safe to establish a direct connection between NextJS and MongoDB without any intermediary services?

When it comes to connecting NextJS on a Digital Ocean droplet directly to MongoDB running on another Digital Ocean virtual server, there seems to be conflicting opinions. Some argue against using "full stack" frameworks like NextJS or Angular without an in ...

The Facebook JS SDK is causing an XSS error and returning a "user_denied" response, even though the Auth Popup for FB.Login is not being

I currently have a Facebook canvas app located at Previously, I was using an anchor link to direct users to the OAUTH login flow. After implementing the Facebook JavaScript SDK, I followed this logic: 1) Initialization of the FB API FB.init({ a ...

Encountering this issue in the _document.js file within Next.js

I'm facing an error with my Next.js project while trying to integrate Material-UI. I followed a tutorial and implemented the _document.js code, but the issue persists despite spending hours troubleshooting. Here's a link to the screenshot of the ...

React Router V6 - page is not found in browsing history

Currently, I am encountering an issue with react router v6. While on the detail page, if I press the arrow in Chrome to go back to the previous page, it takes me to the page before the previous one. I checked the history by long pressing on the back arrow, ...

Designing functional components in React with personalized properties utilizing TypeScript and Material-UI

Looking for help on composing MyCustomButton with Button in Material-ui import React from "react"; import { Button, ButtonProps } from "@material-ui/core"; interface MyButtonProps { 'aria-label': string, // Adding aria-label as a required pro ...

Steps for automatically closing the parent dialog when the child dialog is opened in Material UI React

When utilizing Material UI React, a scenario arises where a dialog opens on button click. Once "yes" is clicked in the initial dialog, another dialog pops up on top of the first one. Is there a way to close the parent dialog before launching the child di ...

Utilizing Node.js to retrieve streams in conjunction with OpenAI

I am currently working on setting up a node/react setup to stream results from openai. I came across an example project that accomplishes this using next.js. While I have successfully made the API call and received the results as expected, the challenge li ...

Ways to retrieve the data received from an axios.post request in the server-side code

Currently, I am working on a project that involves using React for the frontend and Spring Boot for the backend. However, I am facing an issue with retrieving data that I have sent using Axios from the frontend to the backend. The code snippet below show ...

Tips on invoking a method from a JavaScript object within an AJAX request

Considering the following code snippet: var submit = { send:function (form_id) { var url = $(form_id).attr("action"); $.ajax({ type: "POST", url: url, data: $(form_id).serialize(), dataType: 'json', succes ...

How to Resolve ENOENT ERROR When Using fs.unlink in an Express.js Simple Application?

Currently, I am developing a basic blog using express.js. For managing the posts, I have opted for Typicode/lowdb as my database. The posts are created, updated, and deleted based on unique IDs stored in a data.json file. Additionally, I utilize the slug d ...

To properly format the date value from the ngModel in Angular before sending it to the payload, I require the date to be in the format

When working with Angular 9, I am facing an issue where I need to format and send my date in a specific way within the payload. Currently, the code is sending the date in this format: otgStartDate: 2021-07-20T09:56:39.000Z, but I actually want it to be for ...

Is there a way to incorporate resizable columns into my React data grid?

I have implemented the DataGrid component from material UI React in my project. However, I am facing an issue with resizing columns as indicated in the documentation. return ( <Box m="1.5rem 2.5rem"> <Typography variant="h ...

Why doesn't Next.js provide an error message for Images missing the src property?

While Next.js is an amazing tool, it can occasionally present frustrating bugs for developers. In my current website project, I have utilized next/image in approximately 25 instances. Unfortunately, I am now encountering the following error message: Erro ...

Arranging elements on top of a fixed element using JavaScript and CSS

Currently, I am implementing Javascript code that adds a div to the body of pages. The purpose of this div is to always stay at the top of the document or window, regardless of the page's design and content. Everything was functioning correctly until ...

Tips on how to update the styling of an active link

http://jsfiddle.net/G8djC/2/ Looking to create a tabbed area where content changes based on the tab clicked. The Javascript function switches the link class to active upon clicking. However, struggling to change the color of the active tab beyond the firs ...

Discover the way to retrieve PHP SESSION variable within JavaScript

I'm currently working on developing a platform for image uploads. As part of this project, I assign a unique identifier to each user upon login using $_SESSION['id'] in PHP. Now, I am looking for a way to verify if the $_SESSION['id&apo ...