Skip to main content

Command Palette

Search for a command to run...

Get URL Query Params in Next.js using getInitialProps()

Published
1 min read
S

Freelance Web & UX Designer from Incredible India. I design and develop creative websites, landing pages and applications for startups and e

As the title says, this is a simple code snippet to get URL Query params in Next.js using getInitialProps() method.

In Next.js, getInitialProps() have context property where URL query can be fetched using query. See example code below.

URL: http://localhost:3000/?title=Awesome&desc=Content

Page.getInitialProps = async (context) => {
  return { 
    title: context.query.title, 
    desc: context.query.desc 
  };
};

Now we can get these values in our function like this:

export default function Page({ title, desc }) {
 return (
    <>
       Title: {title}
       Desc: {desc}
    </>
}
4.8K views