Utilizing Next.js for dynamic routing with [[...slug.js]] allows for comprehensive URL handling and seamless 404 page display for links leading back to the homepage - a feature

In order to achieve a single dynamic route for handling all requests in this application, I have created a file called [[...slug]].js. Data loading is managed using getServerSideProps(), allowing for server-side rendering. Notably, there are no index.js files present.

While everything functions properly when running locally in development mode, issues arise upon deployment to Vercel. The problem lies in links pointing to /; specifically, using

<Link href={"/"}>
results in a request for an index.json file from the server, triggering a 404 response and displaying an error page. The reason behind this behavior remains unclear.

Answer №1

Ah, I figured it out!

My approach involves utilizing getServerSideProps() to retrieve data based on the slug provided. The content originates from Sanity.io and is queried to determine if the slug property matches either the URL's slug or a default page slug.

During local development using next dev, I encountered an issue where the params.slug argument was showing up as undefined when loading the root ("/") URL. This remained consistent whether accessing the URL through a refresh or navigation action (like clicking a link or using the back button).

However, things took a twist once the site was deployed. While the initial load still returned undefined for params.slug, any subsequent client-side navigation led to the slug mysteriously changing to index. As I had not accounted for a page with a slug of index in my setup, this unexpected behavior resulted in 404 errors. The solution? Including "index" as one of the triggers for the default slug resolved the issue.

Whether this is a quirk in Next JS or simply a gotcha that caught me off guard remains uncertain, but it certainly kept me scratching my head for some time.

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

Unable to post form data into database due to Javascript undefined data situation

I've been working on an HTML form that can interact with a PHP API to retrieve client data and then update user stats in a MySQL database. Currently, I am converting the data into a JSON object and using JSON.stringify to create a string for sending ...

What methods do publications use to manage HTML5 banner advertisements?

We are working on creating animated ads with 4 distinct frames for online magazines. The magazines have strict size limits - one is 40k and the other is 50k. However, when I made an animated GIF in Photoshop under the size limit, the image quality suffered ...

Navigating to redirected URL within jquery's get() function

When I tried sending a get request to a Google App Script URL in my application using JQuery's get method, everything was working fine. However, out of the blue, that API started redirecting to a different URL in case of an authentication error. As a ...

Get the final element with a for loop in Angular 2

I am currently utilizing angular 2 in conjunction with mongoDb. The service I am employing is responsible for calling the API. Here is a snippet of my code: this.at represents a token, similar to fdfdsfdffsdf... This token serves as an authorization key ...

Typescript is throwing a fit over namespaces

My development environment consists of node v6.8.0, TypeScript v2.0.3, gulp v3.9.1, and gulp-typescript v3.0.2. However, I encounter an error when building with gulp. Below is the code snippet that is causing the issue: /// <reference path="../_all.d. ...

Learn the steps for submitting and interpreting information in Node Express

I am attempting to send this JSON data to a node express endpoint { "data": [ [ "Audit Territory", "LA Antelope Valley", "LA Central", "LA East San Gabriel", "LA San Fernando Valley", "LA West", ...

Node.js - Error: JSON.Parse and JSON.Stringify are not recognized as functions

Is it possible to convert a string to JSON and vice versa without any additional npm packages? I am currently using JSON.Stringfy in my router.js file. Are there any specific npm modules that need to be added to the project in order to use the JSON.Stringf ...

The routing navigate method is failing to direct to the desired component

For the past day, I have been struggling to find a solution to my issue but without success. The routing seems to be malfunctioning as it keeps showing the HTML content from app.component.html even when I try changing the path in the URL. Here is a snippe ...

strange issue encountered while utilizing JavaScript's async/await syntax

Recently, I encountered an issue while trying to retrieve a random user from the randomuser API using code in my Vue frontend. // Here is the structure of the API response { info: { // details omitted }, results: [ {//random user data} ] } // This snippet ...

How to make a GET request to a Node server using Angular

I am currently running a node server on port 8000 app.get('/historical/:days' ,(req,res,next){..}) My question is how to send a request from an Angular app (running on port 4200) in the browser to this node server. Below is my attempt: makeReq ...

In JavaScript, there is a missing piece of logic when iterating through an array to find

I am working on a solution to populate empty values when data is not available for specific months. You can view my progress on Plunker here: http://plnkr.co/edit/f0IklkUfX8tkRZrn2enx?p=preview $scope.year = [ {"month":"mar", "val":"23"}, {"month":"feb", ...

Instructions on how to implement a readmore button for texts that exceed a specific character length

I am attempting to display a "Read more" button if the length of a comment exceeds 80 characters. This is how I am checking it: <tr repeat.for="m of comments"> <td if.bind="showLess">${m.comment.length < 80 ? m.comment : ...

I utilized Bootstrap to validate the form, however, despite the validation, the form is still able to be submitted. What steps can I take to

I have implemented form validation using Bootstrap's 'needs-validation'. However, I am facing an issue where the form still gets submitted even when the validation fails. What I want is for the form submission to be prevented if the validati ...

Instructions for concealing and revealing a label and its corresponding field before and after making a choice from a dropdown menu

Currently, I am working on developing a form that will enable customers to input their order information. This form includes a selection list for payment methods, with three available options. If the user chooses either credit or debit card as the paymen ...

Tips for maintaining consistent width of a div:

My current project involves designing a website that displays various quotes, with each quote rotating for a specific amount of time. However, I'm facing an issue where upon loading the page, the first quote triggers the appearance of a scrollbar, mak ...

Is there a way to effectively organize an RSS feed using the .isoDate parameter while ensuring that the feed's elements remain interconnected (such as title and link)?

My goal is to organize the RSS feed by the most recent item while ensuring that each title corresponds correctly with its link. Currently, I am parsing and displaying the feed using the .isoDate property, but I am unsure of the best approach to achieve thi ...

Imitate a hover effect followed by a click to activate the pre-established onclick function

When using Gmail, selecting a message will prompt a bar to appear at the top of the messages table. This bar allows for mass actions to be performed on the selected messages (refer to the GIF photo attached). https://i.stack.imgur.com/XxVfz.gif I have be ...

Nested React Components in React Router Components

class AppRoutes extends Component { render () { return ( <Suspense fallback={<Spinner/>}> <Switch> <Route exact path="/" component={ HomePage } /> <Route exact path="/acti ...

What is the best way to transfer the search query to a table filter when working with multiple JavaScript files?

I am struggling with passing the search query from my search file to my table file. The data for my datagrid table is retrieved from a database using an API call, and the table code is in one file while the search functionality code is in another file. I h ...

javascript loop that runs on every second element only

After completing an ajax query, the following JavaScript code is executed. All of my images are named "pic". <script type="text/javascript> function done() { var e = document.getElementsByName("pic"); alert(e.length); for (var i = 0; ...