question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Next.js useRouter() query: { amp: undefined }

See original GitHub issue

I am having issues passing in query objects to useRouter() hook. I am attempting to capture URL params and pass it into a page component pages/post.js server-side using koa. and koa-router.

I am using Koa.js as my middleware based on next.js example: custom-koa-server and using Next’s documentation: Custom routes (using props from URL)

// server.js

app.prepare().then(() => {
  const server = new Koa();
  const router = new Router();

  router.get("/post/:slug", async ctx => {
    await app.render(ctx.req, ctx.res, "/post", { slug: ctx.params.slug });
    ctx.respond = false;
  });

  router.get("*", async ctx => {
    await handle(ctx.req, ctx.res);
    ctx.respond = false;
  });

  server.use(async (ctx, next) => {
    ctx.res.statusCode = 200;
    await next();
  });

  server.use(router.routes());
  server.listen(port, () => {
    console.log(`> Ready on http://localhost:${port}`);
  });
});
// pages/post.js

import { useRouter } from "next/router";

const Post = () => {
  const router = useRouter();
  console.log(useRouter());
  const { slug } = router.query;

  return <p>My Blog Post: {slug}</p>;
};

export default Post;

useRoute() console.log

// output: console.log(useRoute());

ServerRouter {
  route: '/post',
  pathname: '/post',
  query: { amp: undefined },
  asPath: '/post/testing' }

When attempting to access the query object, no matter what, I get { amp: undefined }

Any help on this will be super helpful! Thank you in advance!

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:14
  • Comments:10 (4 by maintainers)

github_iconTop GitHub Comments

49reactions
bduffanycommented, Apr 16, 2020

It seems a bit user-unfriendly that the router.query is not properly initialized until first render. What’s the technical reasoning behind this?

14reactions
chancedcommented, Apr 29, 2020

@jingyuanhe

All you need to do to resolve this is useEffect to make sure it runs after router has initialized.

For example:

  const [queryId, setQueryId] = useState(null)
  useEffect(()=> {
    if(router && router.query) {
      setQueryId(router.query.id)
    }
  }, [router])
Read more comments on GitHub >

github_iconTop Results From Across the Web

useRouter/withRouter receive undefined on query in first render
I found something: isReady: boolean - Whether the router fields are updated client-side and ready for use. Should only be used inside of ......
Read more >
next/router | Next.js
useRouter is a React Hook, meaning it cannot be used with classes. You can either use withRouter or wrap your class in a...
Read more >
Fixing Next.js router query param returning undefined on ...
First, let's just try to reproduce this issue. You might encounter some cases where you need access to query params of a route....
Read more >
How To Parse Query String Parameters in Next.js - Upmostly
Just like through the front-end with useRouter(), we get an object back containing all of the query parameters provided, which you can then...
Read more >
How to use the next/router.useRouter function in next - Snyk
zeit / next.js / test / integration / dynamic-routing / pages / blog ... const router = useRouter() const { name, id }...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found