Target Active Link when the route is active in Next.js

A simple solution based on the useRouter hook:

import Link from "next/link";
import { useRouter } from "next/router";

export const MyNav = () => {

  const router = useRouter();

  return (
      <li className={router.pathname == "/" ? "active" : ""}>
        <Link href="/">home</Link>
      <li className={router.pathname == "/about" ? "active" : ""}>
        <Link href="/about">about</Link>

You could also use router.asPath instead of router.pathname if you want to include the url query parameters. This can be useful if you want to handle anchor tags such as /#about.

First, you need to have a component called Link, with temporary attribute activeClassName

import { useRouter } from 'next/router'
import PropTypes from 'prop-types'
import Link from 'next/link'
import React, { Children } from 'react'

const ActiveLink = ({ children, activeClassName, ...props }) => {
  const { asPath } = useRouter()
  const child = Children.only(children)
  const childClassName = child.props.className || ''

  // pages/index.js will be matched via props.href
  // pages/about.js will be matched via props.href
  // pages/[slug].js will be matched via
  const className =
    asPath === props.href || asPath ===
      ? `${childClassName} ${activeClassName}`.trim()
      : childClassName

  return (
    <Link {...props}>
      {React.cloneElement(child, {
        className: className || null,

ActiveLink.propTypes = {
  activeClassName: PropTypes.string.isRequired,

export default ActiveLink

Then have a navigation bar with created component Link and css selector :active to differentiate between active and inactive link.

import ActiveLink from './ActiveLink'

const Nav = () => (
    <style jsx>{`
      .nav-link {
        text-decoration: none;
      .active:after {
        content: ' (current page)';
    <ul className="nav">
        <ActiveLink activeClassName="active" href="/">
          <a className="nav-link">Home</a>
        <ActiveLink activeClassName="active" href="/about">
          <a className="nav-link">About</a>
        <ActiveLink activeClassName="active" href="/[slug]" as="/dynamic-route">
          <a className="nav-link">Dynamic Route</a>

export default Nav

After that, you can implement the navigation bar to your page:

import Nav from '../components/Nav'

export default () => (
    <Nav />
    <p>Hello, I'm the home page</p>

The key of how does this work is located inside component Link, we compare the value of router.pathname with attribute href from the Link, if the value match the other then put specific className to make the link looks activated.

Reference: here