Skip to content
Advertisement

How to pass query parameters to next.js api handler when calling from inside of getStaticProps

I am under the impression that you can import api request handlers and call them directly inside of your getStaticProps function because of the documentation where it says:

Note: You should not use fetch() to call an API route in your application. Instead, directly import the API route and call its function yourself. You may need to slightly refactor your code for this approach.

I have an api route at /api/user/[id].js and the implementation looks something like this:

export default function user(req, res) {
  const userId = req.query.id;
  const user = getUserById(userId);
  res.json(user);
}

If I want to use this handler in the getStaticProps of another page in the front-end such as /admin/user/[id].js how would I pass the id query to the request handler? Calling it without any parameters doesn’t work and throws an error saying that req.query.id is undefined.

import userHandler from "../../api/user/[id].js";

export async getStaticProps(){
    // This is where the api handler is getting called
    const user = await userHandler();
    return { props: { user } }
}

Advertisement

Answer

Here is what I would suggest to do in order to make stuff work:

  1. you do not need “dynamic” name for the file with your api calls handlers (instead of /api/user/[id].js you can create /api/user.js);
  2. you need specify a page (file) for user details view. It should be created in /pages/user/[id].js and paste getStaticProps function there. Now once you change url in browser to http://localhost:3000/user/whatever getStaticProps will be called with ({ params: {id: ‘whatever’}})

getStaticProps – gets context argument which consists of several properties. All the dynamic URL parts will be stored under params property, taking into account above part this should work:

export async getStaticProps({ params }){
    const user = await user(params.id);
    return { props: { user } }
}

If you need some additional explanation you are welcome to ask

Advertisement