Trees4theForest
Trees4theForest

Reputation: 1396

Inconsistent static links with Next.js SSG

I've created a Next.js website with the simple structure:

- pages
  - articles
    - [slug].js
    - index.js

- components
  - nav.js

In nav.js, I route all links with next/link as well as in pages/articles/[slug].js and pages/articles/index.js <-- The latter is an "archive" page of sorts to see all articles.

However, I can't get Link to properly point to domain/articles/ and have the generated links in that list work properly.

With each <Link /> I'm using the <Link href="/articles/[id].js" as={/articles/${id}}> method which works in development, but as soon as I export to a static site, issues abound.

First, setting a static link doesn't seem to work at all:

<Link href="/articles/index.js" as={`/articles/${id}`}> results in a link pointing to domain/articles which gives me the index of files in the generated articles/ folder. If I manually add an .html to the end, then I get the page. However, the same link in a generated articles/[id] page link, points to domain/articles/articles

I think I must be doing something wrong, but I can't for the life of me figure out how I'm supposed to use the <Link /> component to generate consistent and functional static links between pages.

Upvotes: 0

Views: 973

Answers (2)

Jesper We
Jesper We

Reputation: 6087

[UPDATE: Newer version of NextJS do no longer require the use of the as attribute.]

First of all, the href attribute should not have the .js file suffix.

Correct hrefs for your example files would be href="/article" and href="/article/[slug]"

Secondly, your as attribute needs to match with the href, so you can not do for example

<Link href="/articles/index" as={`/articles/${id}`}>

since "index" does not match with the id string.

So correct tags are:

<Link href="/articles">

(Does not need as since it is the same as the href)

<Link href="/articles/[slug]" as={`/articles/${id}`}>

It should work better for you once you correct those things.

Upvotes: 2

Trees4theForest
Trees4theForest

Reputation: 1396

Turns out the issues stemmed from a quirk of Next.js deployment: It does NOT support having the site in subfolders. So example.com/myNextSite/ will do strange things with links, while the same exported site works fine in the root example.com.

Upvotes: 0

Related Questions