Is there a way to extract query parameters from the URL using getInitialProps?

There is a neat URL with query parameters that I am working with.

http://localhost:3000/post/:id

My goal is to extract the 'id' query parameter on the client side.

static async getInitialProps({req, query: { id }}) {
    return {
        postId: id
    }
}

render() {
  const props = { 
       data: {
          'id': this.props.postId        // 'id' is currently undefined
       }
  }
  return (
     <Custom {...props}>A component</Custom>
  )
}

This is how my Express endpoint is set up.

app.post(
    '/post/:id',
    (req, res, next) => {
        let data = req.body;
        console.log(data);
        res.send('Ok');
    }
);

However, the output on the server side shows this.

{ id: 'undefined' }

I have searched through the documentation and GitHub issues but I am unable to figure out the reason behind this issue.

Answer №1

The correct approach for your frontend code is to fetch the post id from the query string.

On the other hand, your backend code needs some adjustments. You should start by using a GET route to render a Next.js page. Make sure to extract the path parameters in order to create the final query parameters by combining both the regular query parameters and the path parameters. Here is an example using express:

const app = next({ dev: process.env.NODE_ENV === 'development' });
app.prepare().then(() => {
  const server = express();
  server.get('/post/:id', (req, res) => {
    const queryParams =  Object.assign({}, req.params, req.query);
    // assuming /pages/posts is where your frontend code lives
    app.render(req, res, '/posts', queryParams);
  });
});

For more information, you can refer to this example on Next.js: https://github.com/zeit/next.js/tree/canary/examples/parameterized-routing.

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

Executing a JavaScript function with jQuery

function launch() { $("p").text("Hey there", greet()); } function greet() { alert("Greetings! You have triggered another function"); } HTML: <p>This is a paragraph.</p> <p>This is another paragraph.</p> <button onclic ...

Ensure the backslashes are removed from the AWS Lambda string API response

I have an AWS Lambda function where I am sending a string as my final response let abc= `"phone_exist":"0","calls":"0","lastaction":"0"` callback(null,abc); Output: "\"phone_exist\":\"0\",\"calls\":\"0\",\"l ...

Uniform Height for Several Selectors

I came across a script on Codepen created by RogerHN and decided to customize it for a project I'm currently working on: https://codepen.io/RogerHN/pen/YNrpVa The modification I made involved changing the selector: var matchHeight = function ...

Ways to make React detect a click event triggered by Jquery

I'm currently utilizing dabeng/OrgChart within a React application. The functionality I am looking to achieve is when a user clicks on a node, instead of Jquery populating an input box, I want React to save the selected node in state. I have attempte ...

Sharing asynchronous data between AngularJS controllers

Among the multitude of discussions on sharing data between controllers, I have yet to come across a satisfactory solution for my particular scenario. In my setup, one controller fetches data asynchronously using promises. This controller then creates a co ...

Performing additions on two-dimensional arrays using Angular/JavaScript

Currently, I am in the process of learning basic JavaScript and could use some assistance. My task involves working with two-dimensional arrays where the 0th index will always represent a date and the 1st index will always be an integer in the array. My go ...

Troubleshooting NodeJS and Express: Issue accessing a function located outside a folder

I'm having trouble accessing the function I exported in app.js Here is the code snippet from app.js: function getConnection() { return mysql.createPool({ host: 'localhost', user: 'root', password: &apo ...

What is the best way to transfer the window object from the current tab to the extension?

I am looking to retrieve user storage data (local and session) from a specific tab, similar to what is shown in this app (see screen below). From my understanding, I need to access the window object of the active tab. While I have obtained the object, I a ...

Placing a div over a JavaScript element

Is it feasible to overlay a div(1) with a background image on top of another div(2) that contains JavaScript (like Google maps API v3)? I have experimented with z-index without success, and I am unable to utilize absolute positioning because I depend on t ...

Having trouble importing from the public folder in CSS with Create React App?

While working on a project initialized with Create React App, in the public folder there is an assets directory containing a file named logo512.jpg. When I use this file in a component like so: <div> <img src='/assets/logo512.jpg'/& ...

When it comes to utilizing the method ".style.something" in JavaScript

Here is some javascript code that I am working with: function createDiv(id){ var temp = document.createElement('div'); temp.setAttribute("id", id); document.getElementsByTagName('body')[0].appendChild(temp); } c ...

Access to a custom Google Map via an API connection

I currently have multiple custom Google Maps that I created using and they are all associated with my Google account. Is it possible to access these maps using the Google Maps JavaScript API? It seems like the API does not work with manually created maps ...

Guide on utilizing popup box input to amend CSS (background color)

I'm looking for some guidance on JavaScript and CSS. Is there a way to create a popup box where users can input a color (any main primary color recognized by CSS) and then have the background color of the page change accordingly in an external styles ...

Navigating with firebase authentication and angular routing

Currently, I am in the process of developing an ionic app using version 4. For this project, I have decided to utilize firestore as my database and implement firebase-authentication for user login and registration functionalities. However, I have encounter ...

Error: Attempting to assign a value to the property 'running' of an undefined variable

While working with Nuxt.js, I encountered an issue related to reading the running property of my client object. Here is the HTML code snippet: <b-button v-show="!(projectSelecter(project.ID)).isStarted" //this work just fine variant="success" c ...

Filtering in JavaScript arrays based on conditions that are not related to the elements in the array

Consider the following code snippet: var numbersArray = [1, 3, 6, 8, 11]; var returnedArray = numbersArray.filter(function(number) { const condition = false // or true sometimes return number > 7 && condition ; }); console.log(returnedArra ...

Develop a React npm package with essential dependencies included

I have been working on developing a UI library using React ts. As part of this project, I integrated an external library called draft-js into the package. However, when I attempt to implement my library in another project, I keep encountering errors. Despi ...

Control the value dynamically with Powerange using JavaScript

I have incorporated the Powerange library into my form for creating iOS style range bars. This javascript library offers a variety of options provided by the author. Is there a method to programmatically move the slider to a specific value using JavaScrip ...

Verify the presence of blank space with javaScript

I currently have a text box on my website. <input type="text" name="FirstName" value="Mickey"> My goal is to prevent the user from entering empty spaces, tabs, or new lines in the text box. However, I want to allow spaces between characters. Does a ...

What is the best way to utilize the $('input').on('change', function() method within AngularJS?

I am working on creating a registration form page using AngularJS and I need to display the percentage completed. The form consists of over 50 fields, so I am looking for a simple way to implement this functionality. Below is a snippet of the code I have ...