Unreliable static URLs with Next.js static site generation

I've recently built a Next.js website with the following structure:

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

- components
  - nav.js

Within nav.js, I have set up routing for all links using next/link, including in pages/articles/[slug].js and pages/articles/index.js <-- The latter serves as an "archive" page to display all articles.

However, I am facing issues getting Link to correctly direct to domain/articles/ and ensuring that generated links within that list work properly.

In each <Link />, I am incorporating the

<Link href="/articles/[id].js" as={
/articles/${id}}> approach, which functions during development. However, upon exporting to a static site, complications arise.

Initially, establishing a static link proves ineffective:

<Link href="/articles/index.js" as={`/articles/${id}`}>
leads to a link directing to domain/articles, showing me the index of files in the generated articles/ directory. By manually adding ".html" at the end, I am able to access the page. Yet, when the same link is utilized within a generated articles/[id] page link, it points to domain/articles/articles.

I can't seem to pinpoint where I may be going wrong, and I am struggling to understand how to effectively leverage the <Link /> component to establish consistent and operational static links between pages.

Answer ā„–1

[UPDATE: The most recent NextJS versions no longer necessitate the use of the as attribute.]

To begin with, the href attribute should not contain the .js file extension.

The proper hrefs for your sample files would be href="/article" and href="/article/[slug]"

Secondly, the value of your as attribute must correspond with the href, meaning you should not do something like

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

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

Therefore, the correct tags are:

<Link href="/articles">

(No need for as since it matches the href)

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

If you make these corrections, it should work more effectively for you.

Answer ā„–2

It appears that the problems originated from a peculiarity in Next.js deployment: It does NOT allow the site to be placed in subfolders. This means that example.com/myNextSite/ will cause unexpected behavior with links, whereas the same exported site functions properly when located at the root example.com.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can I create a dropdown menu that is dependent on another dropdown menu using Ajax in my Laravel application?

I have two dropdown fields that are dependent on each other - Class & Section. I am trying to Select * from sections where class_id=selected Class Id. Although I attempted to achieve this using java script, it doesn't seem to work for me. Here are ...

"Freezing issue with Angular big table causing web page to lock up during

Looking for a way to improve the performance of an HTML table search function that is currently running very slowly and freezing the web page upon loading and searching. The table needs to be within the HTML file itself, not pulling data from a server. Any ...

Tips on sending filter parameters from AngularJS to Spring RestController using @MatrixVariable

Iā€™m struggling to figure out how to use $http.get in AngularJS to pass filter parameters. The URL is: http://localhost:8080/template/users/query;username=abcd;firstName=ding... The RestController looks like this: @RequestMapping(value={"/users/{query ...

Simulating SOAP requests using the Nock library

I have a project in progress involving a node application that interacts with soap services. To handle parsing of JSON into a valid SOAP request and vice versa for the response, I am using the foam module. Everything works smoothly when communicating with ...

What is the correct method for verifying the presence of a field in JavaScript (or its frameworks)?

Is there a better way to rewrite this computed method in JavaScript to handle cases where a field may not be available? computed() { isVerified() { return this.name.info.is_valid; } } I can make it less verbose, but I want it to still functi ...

The hot loader is replicating code multiple times instead of conducting hot swapping

Every time I make a change in a component, webpack recompiles and React hot swaps the module over. However, I've noticed that my code runs multiple times after each hot module swapping occurrence. For example, if I make a change once, the functions ru ...

What could be causing my middleware to fail in safeguarding routes?

I am currently working with next.js and attempting to implement middleware. My goal is to restrict access to certain pages, such as the profile page, if the user does not have a valid token stored in their cookies. However, I seem to be encountering an iss ...

Passing a JSONArray to a webview using addJavascriptInterface can provide valuable data

Within my Android app assets, I have stored an HTML page that I want to display using a WebView and add parameters to the webpage. To achieve this, I populated all the values in a JSONArray and utilized 'addJavascriptInterface' to incorporate th ...

Challenge encountered when rendering markdown in NextJS/React

Having trouble rendering markdown in NextJS/React again. Here's the code I'm using: import ReactMarkdown from "react-markdown"; import gfm from 'remark-gfm'; const PostContent = () => { const source = ` # Hello, ...

Choosing an element with JavaScript

var displayedImage = document.querySelector('.displayed-img'); var thumbBar = document.querySelector('.thumb-bar'); btn = document.querySelector('button'); var overlay = document.querySelector('.overlay'); /* Itera ...

Shopify Redirect Action APP redirects the entire application seamlessly

When using Redirect.Action.APP to redirect the user to another component on the admin side of my app, I encounter an issue where I am prompted to go through the authentication process again, ultimately landing me back at the start of the application. The c ...

Developing a compressed file in JavaScript

async purchaseMultiple(decoded, purchaseData){ const user = await Database.user.findOne({where: { id_user: decoded.id_user }}); if( ! user) return [404, 'ERROR: User [' + decoded.id_user + '] not found']; if(user.credi ...

Is there a way to mount or unmount a React component by pressing a single key?

I am currently developing an application that showcases 3D objects upon pressing certain keys on the keyboard. My goal is to have these objects disappear after 2-3 seconds or once the animation completes. Below is the component responsible for managing th ...

Verify if the username is already in use

Is it possible to validate the existence of a username while the user is entering it in a textbox or immediately after they finish typing? Should I use Jquery or Ajax for this task? Does anyone have any examples demonstrating how this can be done? ...

I keep trying to retrieve a specific property from an object, but every time I do, it returns as undefined

I'm currently employing Javascript within a React component. My goal is to retrieve a specific property from an object. If I log this object out to the console as shown below: console.log("Engine: ", this.Engine); The output looks like th ...

JavaScript errors due to miscalculations Incorrect calculations lead

Here is the formula I am using in my Javascript code: total = parseFloat(unit * rate) + parseFloat(rateamount) + parseFloat(((unit * rate) + (rateamount)) * (tax/100)); The values for the variables are as follows: unit = 5, ra ...

What is the best way to select a cell within the same row using jQuery?

I've successfully implemented a table with a single input field and an AJAX script that triggers when the input field value is changed. Everything is functioning as expected. However, I now face the challenge of adding a dynamic date insertion feature ...

What are the steps to incorporate dynamic routing within Next.js?

After converting my React.js app to Next.js, I am now looking to implement routing to my blog details page upon clicking a card on the blog page. The data is being fetched from a Heroku API. In React, I used react-router-dom for this purpose. Can anyone ...

Efficient method invocation for objects within an array using functional programming techniques

Is there a way to execute a method that doesn't require arguments and doesn't return anything on each object within an array of objects that are all the same type? I've been trying to find a solution without resorting to using a traditional ...

Successfully Determining User Identity with Ajax Authentication

Currently, I am facing a security issue with my login page that uses an Ajax request for user authentication. The password entered by the user is sent as plain text in the form data of the Ajax request, making it vulnerable to interception by sniffing tool ...