How to get the current route in next.js

10695




In this post, we are going to see how to get the current route in next.js.

Getting current route inside react component

To get the current route inside a react component you can simply use useRouter() hook.

Consider you have a route called posts/[id].js

To get the id value you can do like below.

import { useRouter } from "next/router";
export default function Topics() {
    const router = useRouter()
    return (
        <div>
            {console.log(router.query.id)}
        </div>
    )
}

The router.query object will have all the current route info.

Getting current route inside nextjs lifecycle methods

To get the current route inside the nextjs lifecycle methods you can simply use the context object.

Consider you have a route called posts/[id].js

To get the id value inside any lifecycle method, you can do like below.

export async function getServerSideProps(context) {
    const res = await fetch(`http://localhost:5000/posts/${context.params.id}`)
    const data = await res.json()

    return {
        props: {
            data,
        },
    }
}

The context.props will have all the routes.