Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get query params from the url in getInitialProps?

I have a clean url that contains some query param like this.

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

I'm trying to capture the query parameter 'id' on the client side like this.

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

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

My express endpoint looks like this.

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

But my server side console output ends up like this.

{ id: 'undefined' }

I've read the docs and the github issues but I can't seem to understand why this is happening.

like image 751
cocoPuffs Avatar asked Feb 11 '18 21:02

cocoPuffs


People also ask

How do I get query param in Nextjs?

To get the query parameter from the above URL inside the <Items> component, we can use the useRouter() hook in next. js.

How do I get query params from my router?

import ActivatedRoute from '@angular/router'. Inject ActivatedRoute class in constructor. Access queryParams property of ActivatedRoute class which returns an observable of the query parameters that are available in the current URL route.


1 Answers

Your frontend code is correct, fetching the post id from the query string is the way to go.

However your backend code is incorrect, first you need to use a GET route to render a Next.js page, and you must extract the path params to craft the final query params as a combination from both the regular query params as well as those path params, this could look like this 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);
  });
});

Check this Next.js example: https://github.com/zeit/next.js/tree/canary/examples/parameterized-routing for more info.

like image 167
saimeunt Avatar answered Oct 18 '22 07:10

saimeunt