Looking to create dynamic pages on NextJS without relying on fixed paths?

I am looking to create a unique user experience by offering discounts on my website based on the users' citizenship ID numbers. By using their ID number, I can customize the discount amount according to factors such as location, age, and gender.

Users can navigate to mywebsite.com/megadiscount where they can enter their ID number in a form to discover their personalized discount. Additionally, I want them to have the option to visit mywebsite.com/megadiscount/[id number] for the same information.

In order to achieve this with NextJS, I understand that I need to create both megadiscount/index.js and megadiscount/[id].js to handle the ID parameter in the URL.

The challenge arises when dealing with the getStaticPaths function in the megadiscount/[id].js file, as I am unsure of all the possible ID values that will be generated.

This is how my megadiscount/[id].js file is structured:

const Page = ({discount}) => {
  return (
    <>
      <h1>You are eligible for a {discount}% discount!</h1>
    </>
  )
}

export async function getStaticPaths() {

  return {
    paths: [], // Unable to anticipate all potential ID values here
    fallback: false,
  };
}

export async function getStaticProps(context) {
  const { slug = "" } = context.params;
  const discount = fetchDiscountFromServer(slug)
  return {
    props: {
      discount
    },
  };
}

export default Page;

Answer №1

export default function DisplayDiscount({ discount }) {
  return (
    <>
      <h1>You qualify for a discount of : {discount}%</h1>
    </>
  );
}

export async function fetchDiscount({ params: { id } }) {
  //Retrieve the discount based on the provided id
  const discount = await retrieveDiscountFromServer(id);
  return {
    props: { discount },
  };
}
export async function determineStaticPaths() {
  return {
    paths: [],
    fallback: "blocking",
  };
}

NextJS introduces fallback:"blocking" handling mechanism for scenarios such as this. Take a look at the documentation

However, considering server-side rendering (SSR) might be more suitable in this context. Static pages would be generated for each user, which is acceptable. Yet, if the discount information changes frequently, adjusting the revalidate:1 option with lower values may help to keep it relatively updated although not in real-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

The checkbox is displayed as selected after being clicked in conjunction with another checkbox

In the tree structure, there are checkboxes that behave strangely when clicked. I have already read a similar discussion here. The problem I am encountering is that when I click on an item, it gets checked but the console does not show it as checked immed ...

Pass information from an array of objects to a visual component

My objective is to display 3 instances of the SearchItem component from locations[0].results[0] and 3 instances from locations[0].results[1] I have an array containing objects with data that I want to display in my SearchItem component: const locations = ...

Error encountered when using the Jquery append function: Anticipated ')' issue

While working on my PHP file, I encountered an issue with an AJAX request. The request is returning the correct value, however, when attempting to use the append function in jQuery, it results in an error being displayed in the console. $.ajax({ ...

What is the best way to configure a basic firebase ajax call?

I wanted to explore using AJAX instead of set to interact with Firebase. However, when I attempted to do so with the code below in my test.html file, I encountered an error message in the console: XMLHttpRequest cannot load . No 'Access-Control-Allow ...

Prevent the box from closing automatically after submitting a form using jQuery

Despite my efforts to keep a simple dialog box open after submitting a form, it continues to close. I tried using the preventDefault method in jQuery, but it didn't solve the issue. Below is the code snippet: $(document).ready(function(e) { $(&apo ...

Limited functionality: MVC 5, Ajax, and Jquery script runs once

<script> $(function () { var ajaxSubmit = function () { var $form = $(this); var settings = { data: $(this).serialize(), url: $(this).attr("action"), type: $(this).attr("method") }; ...

Issue encountered while managing login error messages: http://localhost:3000/auth/login net::ERR_ABORTED 405 (Method Not Allowed)

I am working on the /app/auth/login/route.ts file. import { createRouteHandlerClient } from '@supabase/auth-helpers-nextjs' import { cookies } from 'next/headers' import { NextResponse } from 'next/server' export async functi ...

Encountering a node globby error when implementing multiple patterns

Currently, I am successfully using node glob for folder1 as shown below: glob('folder1/*.js'), function(err, files){ if (err) { console.log('Not able to get files from folder: ', err); } else { files.forEach(function (file) ...

Is it recommended to use Promise.await over async/await?

After starting some new operations in my project, I discovered that db.aggregate needed to be executed asynchronously: db.aggregate( [ { $match: { "records": { $e ...

Is there a way to dynamically toggle the visibility of a floating textarea between on and off?

I have my own blog website: Essentially, what I am aiming for is When a user clicks on the search button, a floating semi-transparent textarea window should appear inside the designated rectangle area (as shown in the image, that red orange rectangle). ...

"Modify the MySQL database each time a user changes the value in a

As a student, I am looking to update value(s) whenever a student changes the value(s) in the correction or update form. So far, I have been able to retrieve and display values in text boxes based on the name selected from a dropdown list from the database ...

Unable to locate the module 'winston'

Developed a small module that utilizes winston for logging purposes. Installed winston using sudo npm install -g winston (since it's on a virtual machine, not too concerned with sudo permissions). NPM log: <a href="/cdn-cgi/l/email-protection" c ...

Choosing a single radio button value within a nested ng-repeat loop in AngularJS

Help needed with selecting only one radio button value in nested ng-repeat. Please review the source code and suggest any potential mistakes. <form ng-submit="save()"> <div ng-repeat="x in surveyLst"> <div class="row"> < ...

What is the best way to create a toggle effect for a <nav> bar that appears from beneath a div?

I need assistance with a navigation setup where the nav (located inside the header) needs to be connected to the bottom of a div named .menu_bar. The desired behavior is for the nav to slide down from directly underneath the .menu_bar when toggled, but cur ...

A customizable JavaScript NPM Package designed to specifically escape XML special characters while preserving the integrity of the XML tags

Seeking recommendations for a JavaScript npm package that can escape the values in an XML document while preserving the XML tags. Ideally, looking for a solution that only allows letters A-Z (upper and lower case), digits 0-9, and spaces within the value ...

An unusual problem encountered with JSON and PHP

Is there a specific reason why a JSON string fails to be evaluated (transport.responseText.evalJSON();) on the server but works fine on my local setup? I'm making a simple AJAX request like this: new Ajax.Request( this.saveUrl, { ...

What is preventing me from retrieving the parameter in the controller?

I could use some assistance with implementing pagination for displaying data. However, I am encountering issues in retrieving the parameter in the Controller Method. To provide more context, I have created a demo on CodePen which can be viewed at http://c ...

What methods can be used to block the input of non-numeric characters in a text field?

I stumbled upon this particular inquiry. Although, the majority of responses involve intercepting key presses, checking the key code, and halting the event if it does not match an acceptable key code. However, there are some issues with this approach. ...

Creating a visual comparison by using knockout side by side

I'm currently working on a project that requires me to display multiple items side by side for comparison. The ideal layout would be similar to Amazon's, where each item is represented by a vertical column with all relevant information about tha ...

Trouble arises when using Wijmo's valueChanged event and data binding in Angular 2

As I was working on the following code snippet that triggers a function when the user modifies the wj-input-time value: @Component({ selector: 'my-app', template: '<wj-input-time [step]="1" (valueChanged)="test()"></wj-inpu ...