Next.js Discord

Discord Forum

Help accessing URL query params for dynamic route in _app file

Answered
Scottish Fold posted this in #help-forum
Open in Discord
Scottish FoldOP
I have the following in my _app file:

MyApp.getInitialProps = async (appContext: AppContext) => {
  const { ctx }: any = appContext;
  const { req, query } = ctx;
  console.log(query);


On a page like pages/test/[foo].tsx the output of the query log has the route params instead of the URL query params. It shows:

http://localhost:3000/test/abc?hello=world
{
  foo: 'abc'
}


I was expecting the output of query log to be:

{
  hello: 'world'
}


Does anyone know why the query output is showing they dynamic route params instead of the URL query params? If it helps, I'm running Next v12.1. I can provide more details as necessary. Thanks in advance!
Answered by Ray
and you should use the getInitialProps in pages/test/[foo].tsx if you are trying to get the URL query params for pages/test/[foo].tsx
View full answer

12 Replies

Answer
Scottish FoldOP
Thanks for the reply @Ray . I forgot to mention that this particular page is static using SWR. So if I'm not mistaken I can't use the getInitialProps along with getStaticProps in the page file. I was also hoping to take advantage of the _app file so that I could run the logic in there on every page
Scottish FoldOP
Okay, it sounds like what I'm trying to accomplish isn't possible for server side then. I was hoping to be able to use the query parameters on the server, but it sounds like that may not be possible. Thanks for the help!
Scottish FoldOP
Yes, they're static, but not being generated at build time. I'm using SWR/ISR for it, so I was hoping that since it needs an initial request to build the page, that it would have access to the query parameters at that point if any were included in that initial paid request
I think I have a potential workaround that I can use. I was just hoping that maybe I was doing something wrong and the query parameters would be available to me within the context here.
Scottish FoldOP
Okay, it looks like I'm not doing anything wrong, but rather it's just a limitation that I'm hitting. Thanks for the information!