0

I'm running this code on a node.js development server:

import { useRouter } from 'next/router'
import nextBase64 from 'next-base64';
   
const Load = () => {
  const router = useRouter()
  const { obj } = router.query
  var decoded = nextBase64.decode(obj)

  return <p>Post: {decoded}</p>
}

export default Load

When I navigate to the page, which is a base64 encoded string, It tells me:

Server Error

TypeError: The first argument must be of type string or an instance of Buffer, ArrayBuffer, or Array or an Array-like Object. Received undefined This error happened while generating the page. Any console logs will be displayed in the terminal window. Source

pages/media/load/[obj].tsx (15:16) @ Load

  13 | const router = useRouter()
  14 | const { obj } = router.query
> 15 | var decoded = nextBase64.decode(obj)
     |              ^
  16 | 
  17 | return <p>Post: {decoded}</p>
  18 | }

However, if I remove the nextBase64.decode(obj) and print the obj it works, printing the encoded string. But here's the kicker. When I revert the change it also works and prints the decoded string.

I think the import nextBase64 from 'next-base64'; statement isn't imported in time for when the function is exported.

What is best practice here, should I do some kind of await import (I tried and failed) or should I import inside the function somehow?

firelynx
  • 30,616
  • 9
  • 91
  • 101
  • 2
    this is the normal behavior of [`router.query`](https://nextjs.org/docs/api-reference/next/router#router-object) if you're not using `getServerSideProps` or `getStaticProps`. or you can use `router.isReady` inside of `useEffect`. see this [codesandbox example](https://codesandbox.io/s/epic-lumiere-b94rw4?file=/pages/media/load/%5Bobj%5D.js:0-483) – mocherfaoui Nov 17 '22 at 17:22
  • 1
    @mocherfaoui Thank you, that helped me solve the issue. Do you want to make that a proper answer so I can green checkbox it or shall I? – firelynx Nov 18 '22 at 06:34
  • sure! I added the comment as an answer – mocherfaoui Nov 18 '22 at 10:29

1 Answers1

1

this is the normal behavior of router.query if you're not using getServerSideProps or getStaticProps. or you can use router.isReady inside of useEffect.

see the below codesandbox example

Edit epic-lumiere-b94rw4

mocherfaoui
  • 902
  • 1
  • 2
  • 11