A different approach to routing in Next.js with getServerSideProps

Let's say I have a dynamic route in my application, with the name [id]

Typically, I use getServerSideProps in the pages router to validate any properties passed to the route. It usually looks something like this:

export async function getServerSideProps(ctx: GetServerSidePropsContext) {

    const { locale, query } = ctx

    //Validate query id
    const id = parseInt(query.id as string, 10)
    
    if(isNaN(id)) {
        return {
            notFound: true
        }
    }
    else {
        //Include logic here to validate the id against the API or pass it as props to the client
    }
}

I find this method useful for maintaining separation, but I'm unsure how to achieve similar results with the app router. The documentation is unclear to me on this matter.

Answer №1

Within the application router, your "pages" serve as server components that can operate asynchronously. The implementation of the logic in this context may appear something like the following:

import { notFound } from "next/navigation";

interface Props {
  searchParams: { id?: string, locale?: string },
}

export default async function Page(props: Props): Promise<JSX.Element> {
  const { id, locale } = props.searchParams;

  // The use of "notFound()" does not necessitate a return statement
  if (isNaN(parseInt(id as string, 10))) notFound();

  // A simulated network request is included for illustrative purposes
  const response = await fetch(`https://example.com/users/${id}`);
  const json = await response.json();

  return (
    <pre>
      <code>{json}</code>
    </pre>
  );
}

This approach demonstrates how you do not always require a separate function to handle networking and validation logic, but it is also possible to define these functionalities within or outside of the component itself.

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

What is the best way to restrict a mapped type in typescript to only allow string keys?

In the Typescript documentation, I learned about creating a mapped type to restrict keys to those of a specific type: type OptionsFlags<Type> = { [K in keyof Type]: boolean; }; If I want to use a generic type that only accepts strings as values: t ...

Encountering issues with deploying a NextJS application using GitHub Actions

I'm currently facing an issue while attempting to deploy my nextJS application on GitHub pages. The error occurs during the deployment phase. Within my node.js.yml file, I have the following configuration: name: Node.js CI on: push: branches: ...

Discovering the data types for node.js imports

When starting a node.js project with express, the code typically begins like this - import express = require('express') const app = express() If I want to pass the variable 'app' as a parameter in typescript, what would be the appropri ...

Troubleshooting: HTTP client post request working with body.set but not with formData.append for sending data to API

I am in the process of updating the UX for an older application with APIs developed in ASP.NET When I make a POST request as shown below, everything works perfectly. The data is received: var APIURL = sessionStorage.getItem('endpoint') + "/ ...

Retrieve the Ionic storage item as a string

My issue is related to the code snippet below: this.storage.get('user') Upon execution, it returns the following object: t {__zone_symbol__state: null, __zone_symbol__value: Array(0)} I am uncertain about how to handle this object. Is there ...

Determine the data type based on the object property

Can a versatile function be created to automatically determine the type based on an "external" object property? Consider the following scenario: const resolversMap: { overallRankingPlacement: (issuer: number, args: Record<string, any>, context: Re ...

The localhost is not updating on subsequent runs of npm run dev after the initial run

Every time I launch npm run dev (for my nextjs application), it functions properly on the initial run. However, after making modifications to my files, saving them, and checking my localhost, the changes do not appear. What is the solution? Currently, I f ...

Showing the outcome of the request from the backend on an HTML page using the MEAN stack

I am currently in the process of developing an angular application with a node.js + express backend. After successfully retrieving the necessary data from MongoDB and being able to view it through terminal, I encountered a challenge when trying to display ...

Leveraging the power of Next.js and a tailored deployment strategy using Express and Node

Recently, I encountered an issue while trying to deploy my app that utilizes Next.js on the frontend (including some getStaticProps function) and a custom express/node.js backend on Azure. The backend is connected to MySQL, although I don't believe th ...

Implementing asynchronous data sharing within an Angular 2 service

I seem to be facing a challenge that I can't quite figure out. My goal is to share data asynchronously between components that I receive from a server. Here is an example of what my service code looks like: import {Injectable} from 'angular2/co ...

Failed to handle webhook POST request even after receiving a successful POST request from Stripe in the command line interface using NextJS 14

I am successfully receiving Stripe webhooks POST requests, but I am facing challenges in handling the requests. I'm unable to see console.logs in the terminal. Is there something I am overlooking? Below is my current code outlining how I want to hand ...

Display an API generated popup list using Vue's rendering capabilities

I'm attempting to generate a pop-up within a displayed list using custom content retrieved from an API request. Currently, my code looks like this: <template> <div class="biblio__all"> <a v-for="i in items" ...

Can we handle optional properties that are contingent on a boolean in the type?

My current scenario involves a server response containing a boolean indicating success and optional data or error information. type ServerResponse = { success: boolean; data?: { [key: string]: string }; err?: { code: number, message: string }; } Dea ...

Securing routes with server-side validation

I've been experimenting with different methods to secure a route for unauthenticated users, but I'm facing difficulties in implementing it effectively. One common issue I encountered while attempting authentication from getServerSideProps was th ...

"Error: Unable to locate module - 'electron-is-dev'" in my web development project using electron, typescript, and webpack

I'm currently working on a project using Electron, Typescript, and webpack. I am planning to integrate react.js into the project. However, when I ran "npx webpack" in the terminal, I encountered an error message. The error stated that the "electron- ...

Having trouble grasping the concept of Interfaces and dealing with FormGroup problems in Angular?

Apologies if my question is a duplicate, I have found several solutions for the same issue on Stack Overflow, but unfortunately, I struggle to understand them in technical terms. Problem 1 src/app/models/dataModel.ts:2:5 2 id: number; ~~ The exp ...

"I'm looking for a way to store and fetch TypeScript objects with PouchDB. Any suggestions on

As someone who is new to typescript and web development, I am eager to incorporate PouchDB into my typescript project to store my objects. Despite the lack of documentation, I am struggling to find the correct approach. I have created typescript objects t ...

React Typescript - Unexpected character ',' encountered at line 1005

Currently, I am utilizing Typescript within a React application that integrates with Graphql. Encountering an error: ',' expected.ts(1005) After researching possible solutions, most suggest that the issue might be due to using an outdated ve ...

What could be causing the cyclic dependency problem after upgrading to Angular 9?

I am experiencing an issue with a specific file containing the following code: import { Injectable } from '@angular/core'; import { I18n } from '@ngx-translate/i18n-polyfill'; import { isNumber } from 'lodash'; import { Confir ...

Retrieving server-side data in Next.js

As I dive into the world of Next.js coming from React, I've been able to make things work for the most part. However, when I tried creating a server component to test server-side fetching, I encountered some strange issues. Usually, when I start the ...