Is the "as" decorator in Next.js Link no longer functioning properly with dynamic routes?

My route is dynamic:

test/[id].js

When a user clicks on a link to /test/1, Next.js successfully renders the correct page.

The issue arises when I try to mask the /test/1 URL with something else.

<Link href="/test/1" as="/any/thing/here">

Based on my understanding, the above code should:

  • redirect the user to test/1 and render test/[id].js,
  • conceal the domain.com/test/1 URL behind domain.com/any/thing/here.

However, it does not point to test/[id].js at all, instead returning a 404 error.

Here is the sandbox link with the broken code:

https://codesandbox.io/s/nervous-silence-z62s1?file=/pages/index.js

What am I doing wrong here? I have very complex URLs with many slashes that I need to use with Next.js dynamic routing, and using "as" seems to be the only solution. I'm fairly certain I used this method successfully a few years ago! It appears to have worked for this individual as well: Linking to dynamic routes in Next.js

If Next.js has made any changes, how can I easily recreate this functionality?

Answer №1

In my opinion, it's important to format the href attribute correctly:

      <Link
        href="/test/[id]?id=1"
        // Alternatively
        href={{
          pathname: '/test/[id]',
          query: { id: '1' }
        }}
        as="/any/thing/here"
      >
        <a>Click here for Link to test/1 - Is the 'as' decorator not working properly?</a>
      </Link>

I can't explain why it functions this way, but I came across this method some time ago and have been using it ever since. It seems like there isn't any documentation about it.

Additionally, ensure that a page with the path /any/thing/here actually exists, as otherwise if the user refreshes the page after navigating via client-side, a 404 error may occur.

Answer №2

The Link element in this example utilizes the as prop to produce a visually appealing URL and transmit a concealed ID as a query parameter. By implementing this method, the ID remains hidden in the displayed URL while still being accessible within the components of your Next.js application.

import Link from 'next/link';

const MyPage = () => {
  // Define the hidden ID that needs to be passed
  const hiddenId = 456;

  return (
    <div>
      <h1>My Page</h1>
      {/* Implement Link to generate a user-friendly URL with the concealed ID */}
      <Link href={`/my-page?id=${hiddenId}`} as="/my-page">
        <a>Navigate to My Page</a>
      </Link>
      {/* Insert your page content below */}
    </div>
  );
};

export default MyPage;

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

Ways to send data to a popup in svelte

Hey there, I could really use some assistance with my Svelte app. I'm trying to implement a modal and pass a parameter to the modal component in order to customize its content. However, when using the open() function of Modal, we only need to provide ...

Instructions for implementing an inline toolbar in a contenteditable="true" feature

I am currently developing a page that allows users to edit its content directly on the page. To achieve this, I have set the attribute contenteditable="true" for all the elements within the page. My goal is to show an inline toolbar with basic editing op ...

Replace the term "controlled" with "unleashed" when utilizing the file type input

In my app, I have defined multiple states like this: const [state,setstate]=React.useState({headerpic:'',Headerfontfamily:'',Subheaderfontfamilty:''}) And to get an image from my device, I am using the following input: &l ...

What is the best way to use command line arguments within a Node.js script?

As a newcomer to the world of programming, I find myself struggling to make progress despite putting in significant effort. Although it may seem like a trivial question, my lack of progress is becoming frustrating. Currently, I am working on a node.js scr ...

Troubleshooting: jQuery $.post not functioning as expected in certain circumstances

I'm currently experimenting with inserting data into a MySQL database using AJAX and jQuery's $.post method. To test this functionality, I have created the following setup: In my index.html file (which already includes jQuery for various other f ...

Utilize JavaScript to trigger a gentle notification window to appear on the screen

Whenever I click a link on my HTML page, I want a popup element (just a div box) to appear above the clicked link. I have been using JavaScript for this, but I am facing an issue where the popup element appears below the link instead of above it. Can you ...

Trouble accessing Silverlight site due to incomplete loading

There is a site known as that consists of a Silverlight application. Strangely, this site loads on all other computers except mine. I keep encountering the following error: An Error occurred in the Silverlight Application: String was not recognized as a ...

Unable to retrieve AJAX response

I've been working on a page where I'm using AJAX to fetch data based on the selection of radio buttons. The three options available are 'Unapproved', 'Approved' and 'All'. My goal is to display the corresponding user ...

A guide on how to cycle through and modify key-value pairs using a Patch Request in MongoDB

I am working on configuring a patch request for the endpoint "/api/user?username=idHere". This patch request should accept a JSON body and update the user in MongoDB with the new key-value pairs. Currently, the line "{$set: {key: req.body[ ...

Maintain the execution of a Node.js function without reliance on any front-end calls

Looking to continuously generate random data in MongoDB using my NodeJS API without making calls from the client-side. var autoCreate = function(){ var randomNumb = (Math.random()* (10-0) + 0).toFixed(0); var randomThing = randomstring.generate({ ...

How can a JavaScript function be triggered by Flask without relying on any requests from the client-side?

I'm in the process of setting up a GUI server using Flask. The challenge I'm facing is integrating an API that triggers a function whenever there's a change in a specific Sqlite3 database. My goal is to dynamically update a table on the HTML ...

Obtain picture from firebase utilizing react Js

I have attempted multiple methods to download images from Firebase, but the download URL is not functioning as expected. Instead of downloading the image directly, it opens in a new tab. The function used in Firebase: export async function addMedia(locati ...

The req.ip in Express appears to alternate between displaying my local machine address as ::ffff:127.0.0.1 and ::1 in an unpredictable manner

Simply put, the title sums it up. I've spent the last few hours working on a middleware function that uses cookies for authentication, like so: const authRoute = async (req, res, next) => { console.log(req.ip); // additional logic here ...

What is the best way to showcase all tab content within a single tab menu labeled "ALL"?

I have created a tab menu example below. When you click on the button ALL, it will display all the tabcontent. Each tab content has its own tab menu. Thanks in advance! function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = doc ...

"Utilizing the power of Twitter Bootstrap and Snap.js for

I am currently working on integrating Snap.js by jakiestfu with Twitter Bootstrap. I have managed to make it work to some extent (I can slide the content and open a drawer through a click event). However, I am facing a challenge where the drawer content re ...

Incorporating React.js into HTML DOM Elements

As a beginner in react js, I'm facing an issue regarding DOM elements. Within my component, there is a table. When hovering over a cell, I want to highlight both the corresponding row and cell. Additionally, I need to obtain the coordinates of the hov ...

What is the best way to achieve the effect of "overflow: hidden" in three.js or WebGL?

I'm diving into the world of designing a WebGL GUI for my games and I'm keen to explore GPU graphics in more depth, as it offers a smoother experience compared to WebKit CSS rendering. Is there a way to create a scrollview where the internal mes ...

Move a 'square' to a different page and display it in a grid format after clicking a button

I am currently developing a project that allows students or schools to add projects and search for collaborators. On a specific page, users can input project details with a preview square next to the fields for visualization. Once the user uploads the ...

Set up two unique production servers with different environment variables in NextJs

For my Next.js project, I encountered a challenge while deploying a new version of the app to a development server that relies on environment variables from .env.development. Our typical process includes the following steps: Develop the new fe ...

Navigate using history.push with user Logout Icon

Currently, I am utilizing a Material UI icon as a logout button in my project. Here is how I have implemented it: function logout(props:any){ localStorage.removeItem("token"); return( <Redirect to="/login" /> ) //props.history.push("/log ...