Search code examples
javascriptreactjshyperlinknext.jsgithub-pages

Links don't work with Next.js and Github Pages


I recently followed a tutorial on building a single page portfolio with React and Next.js and it all works fine running locally in development.

However, when I deploy it to Github pages, internal links stop working.

    <PrefixedLink href="#about">
      <NavLink>About Me</NavLink>
    </PrefixedLink>

I've tried the the following suggestions available online: Add a next.config.js (this did fix loading images from the public folder) - Mine looks like this:

const pathPrefix = process.env.NODE_ENV === 'production'
? '/React-Portfolio'
: '';

module.exports = {
    assetPrefix: pathPrefix,
    basepatch: "/React-Portfolio",
    env: {
        pathPrefix,
    },
};

There was also the suggestion to prefix all links as github pages has the project name in the path, so I have this:

import Link from 'next/link';

const PrefixedLink = ({ href, as = href, children, ...props }) => (
    <Link
        href={href}
        as={`${process.env.pathPrefix}${as}`}
        {...props}
    >
        {children}
    </Link>
);

export default PrefixedLink;

But this also doesn't work.

On the production site the end result looks like:

<a class="HeaderStyles__NavLink-sc-9w0vkp-5 jlNUaI">About Me</a>

without any href="#about", but if I manually add it via the inspector it works fine.

EDIT Getting rid of the and adding the href to the NavLink (a customized tag) fixed the issue.


Solution

  • Getting rid of the and adding the href to the NavLink (a customized tag) fixed the issue.