Is it possible to create a system in NextJS that utilizes either the path or the query parameter?

Due to historical reasons, there is a need to maintain a blog link structure that resembles /blog?article=id-of-article. However, the goal is to implement pre-rendering with NextJS and have the blog URL appear as /blog/id-of-article.

What is the most effective approach to accommodate this scenario? One option is to set up a permanent redirect or ensure that both URLs lead to the same page. As a newcomer to NextJS, I am uncertain about the best course of action.

Any advice or guidance on how to proceed would be greatly appreciated!

Answer №1

Check out my solution below.

//src/routes/index.js
export async function getServerSideProps(context) {

    const { query } = context;
    console.log(query);

    if (query.post) {
        return {
            redirect: {
                destination: `blog/${query.post}`
            }
        }
    }

    // normal operation
    return { props: {} }
}

With this piece of code, the route will function normally if there is no query parameter named post. However, if there is, it will redirect the page to /blog/:post_id.

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

Why isn't res.send() in Node.js sending the message?

Despite numerous attempts, I am unable to send my response message. It was working briefly, but after some code changes, it stopped functioning. Can anyone provide a solution to this challenging issue? exports.listBoth = function(req, res) { ...

What steps should I take to see my JavaScript code in a web browser?

As a beginner in JS, I'm curious about how to display the results of my code. When I try to use this small snippet of test code, the browser shows a blank page: if ( 11 > 10 ) { console.log("You made it!") } else { console.log("You have ...

AngularJS text area not displaying HTML content

In my Ionic's App, I have a textarea that is used for creating or editing messages. However, I am encountering an issue where the textarea does not render HTML tags when trying to edit a message. I attempted solutions such as setting ng-bind-html and ...

Streaming videos on Xbox One is not supported while in developer mode

Currently, I am facing a challenge with my UWP app that runs a web application made for Xbox One. There is a bug that only appears after approximately 4 hours of streaming video content, causing the app to freeze unexpectedly on the machine. The issue lie ...

Steps to display content post authentication using JWT

Utilizing Nodejs and Express for application development. Utilizing JWT for authentication. I have successfully implemented the JWT-based authentication system and tested it with Postman. However, I am facing an issue when passing the request through the ...

Create a new build for testing and debugging using create-react-app

Currently, I am in the process of developing a web application that utilizes a React frontend and is powered by a golang api layer. Although I do not have extensive experience with Javascript, I find myself struggling with the Node build system. I am loo ...

Dynamically binding image URLs in VUEJS

Below is the JSON data containing button names and their corresponding image URLs: buttonDetails= [ { "name": "button1", "images": [{ "url": "https://localhost:8080/asset/d304904a-1bbd-11e6-90b9-55ea1f18bb ...

Tips for implementing a personalized 410 error page in a Next.js 13 application router

I’m currently working on implementing error handling for 410 status codes in my Next.js 13 application router. I’ve already created a notFound page, which is straightforward to handle with Next.js. However, I’m struggling to find a way to show a cu ...

How can I iterate through a directory containing files and extract the exported JavaScript object from each one?

In my current project using nodejs / nextjs, I have file system access and a folder containing multiple React files: content - blog-post-1.jsx - blog-post-2.jsx - blog-post-3.jsx The task at hand is to extract the frontmatter from each file. My init ...

React throws an error message when the update depth surpasses its maximum limit

I am facing an issue with my container setup where the child container is handling states and receiving props from the parent. The problem arises when I have two select statements in which onChange sets the state in the child container, causing it to re-re ...

A more efficient method for creating a nested array of distinct values using JavaScript

The scenario: My website has a complex html table structure to showcase hierarchical data, with the ability for users to toggle visibility of individual rows. Each row is identified by a dom id consisting of a level number and primary key specific to that ...

Ways to troubleshoot errors that arise while building Next.js with Mui framework

After running npm install @mui/material @emotion/react @emotion/server, I encountered an error while trying to build my Next.js app during linting and type checking. info - Linting and checking validity of types ...Failed to compile. ./node_modules/@mui/ ...

What is the method for inputting multi-line strings in the REST Client extension for Visual Studio Code?

Clarification There seems to be some confusion regarding the nature of the data I am storing. I am developing a code snippet web application using Express.js and MongoDB. The purpose is not to store executable code for later use; instead, I am saving snipp ...

Is it possible to pass a component into a dialogue box in material-ui using React?

Hello, I am currently facing an issue with displaying a chart component within a dialogue box. Despite having the code in place, the chart is not rendering inside the dialogue box as expected. Unfortunately, due to the complexity of the code, I am unable t ...

The ajax response is returning the entire page's html code instead of just the text content from the editor

I've been working with CKEditor and I'm using AJAX to send the editor's content via POST method. However, when I try to display the response in a div, the HTML for the entire page is being returned instead of just the editor's content. ...

Organize database entries by categories for easy navigation

I've developed a web application centered around TV Shows to enhance my understanding of AngularJS. Within my database, I have a table containing various TV shows, each with an assigned category column. For instance, "Dexter" is categorized as "thrill ...

Choose a variety of table rows based on the values of the data attributes that are

Is there a more efficient way to select all rows with data attributes id 1,2.. without specifying each row individually? I need some guidance on the best approach for this. Can anyone help me out? <table id="eTable"> <tr data-empid="A123" data- ...

Error: The reference 'GetServerSideProps' is being incorrectly used as a type instead of a value. Perhaps you intended to use 'typeof GetServerSideProps' instead?

Index.tsx import Image from 'next/image' import Head from "next/head" import { sanityClient, urlFor } from "../sanity" import Link from 'next/link' import {Collection, address} from '../typings'; import ...

The NextJS routing feature displays the [slug] parameter in the URL

I am encountering an issue with my NextJS app's folder structure: - pages - docs - [slug] - index - [id] - index These pages are intended to be dynamic, displaying data dynamically on the UI. This means that users can navigate t ...

Creating an AJAX request in Play 2.x by using a shared button

Although I have successfully utilized AJAX requests in the past using a form and adding return false to prevent page refresh, I recently encountered an issue when moving my JavaScript into a separate file. The @ commands now fail, making it difficult for m ...