What is the process for including a new attribute in NextRequest categories?

I'm currently working on a middleware that will introduce a new "name" property to NextRequest. This specific property is intended for use in other sections of the API.

import { NextRequest, NextResponse } from 'next/server'

export function applyMiddleware(req: NextRequest) {
    req.name = 'Foo'

    NextResponse.next()
}

Encountering the error message

Property 'name' does not exist on type 'NextRequest'

One possible solution could involve creating an interface that extends NextRequest. However, this approach would require importing all files that need access to the "name" property.

import { NextRequest, NextResponse } from 'next/server'

interface CustomRequest extends NextRequest {
    name: string
}

export function applyMiddleware(req: CustomRequest) {
    req.name = 'Foo'

    NextResponse.next()
}

Is there a method to incorporate this property into the global types of NextRequest?

Answer №1

Illustrating my problem-solving approach following the advice provided by juliomalves


To address this issue, create a .d.ts file with any desired name

// custom.d.ts
import { NextRequest as OriginalNextRequest } from 'next/server'

declare global {
    declare interface NextRequest extends OriginalNextRequest {
        name: string
    }
}

Key points to consider:

  • extends OriginalNextRequest is necessary to display all NextRequest types of next

  • It is recommended to rename the import for NextRequest to avoid conflicts in TypeScript when extending it, ensuring that autocomplete suggestions include all properties

Including the modified NextRequest via import statement

// tsconfig.json

"paths": {
    "*": ["*.d.ts"]
}

If the .d.ts file is within a directory

"paths": {
    "*": ["types/*.d.ts"]
}

With these changes, TypeScript will no longer flag errors regarding the absence of name in NextRequest

import { NextResponse } from 'next/server'

export function middleware(req: NextRequest) {
    req.name = 'Foo'

    NextResponse.next()
}

NOTE: Avoid importing NextRequest directly from next to prevent overwriting the global type definition

import { NextRequest, NextResponse } from 'next/server'

export function middleware(req: NextRequest) {
    req.name = 'Foo' // error

    NextResponse.next()
}

If you prefer using NextRequest from next, consider renaming the import

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

When a card is clicked in the parent component, data is sent to the child component in Angular. The card contains an image, name, ID,

How can I pass data from a parent component (nfts) to a child component (main) when a card is clicked? The card contains images, ids, names, and more information. I've attempted using @Input() but haven't been able to receive the value in the ch ...

How to declare and initialize a variable in Angular 2 using TypeScript

I'm currently working with angular 2 and I'm having trouble understanding how to set a variable. The variable _isLoading is being set in "this.observable.filter((event)" but it doesn't seem to change in the template. This is my TypeScript co ...

Tailored component properties for React applications

I am currently working on configuring discriminative component props. Check out my code snippet below: import React, { ReactNode } from 'react' type SelectionModalProps<T> = ( | { multiSelect: true onSubmit: (data: T[]) => ...

Error: JSON input ended unexpectedly, and data retrieval is not possible

Encountering the following error message: SyntaxError: Unexpected end of JSON input https://i.stack.imgur.com/ivG2e.png Modifying the code causes the page to endlessly load without stopping Utilizing Next.js for development The API directory being used ...

Category of ambiguous attributes

I am currently working on developing a class that will store values for rows and columns, with each row/column identified by a string. I have provided some code below as an example: class TMatrix<TYPE>{ [idRow: string]: { [idCol: string]: TYPE ...

Error caused by properties of a variable derived from an interface in the compiler

I'm confused as to why the compiler is saying that the properties "name" and "surname" don't exist on type "ITest1" within function test1. It's a bit unclear to me: interface ITest1{ name: string; surname: string; age: number; } ...

Encountering a Difficulty while attempting to Distinguish in Angular

I am currently working on a form where I need to dynamically add controls using reactiveForms. One specific task involves populating a dropdown menu. To achieve this, I am utilizing formArray as the fields are dynamic. Data: { "ruleName": "", "ruleD ...

What is the correct way to properly enter a Svelte component instance variable?

Currently, I am delving into learning Svelte and specifically exploring how to bind to a component instance as demonstrated in this tutorial: As I progress through the tutorial, I am attempting to convert it to Typescript. However, I have encountered an ...

Navigating with Next.js 13: The correct way to redirect to a dynamic route while ensuring that only the latest data is

Currently, I am working on implementing dynamic redirection from one page to another using Next.js. The goal is to trigger this redirection when a button is clicked. To achieve this functionality, I have created a custom hook as follows: import { useR ...

What steps do I need to take to implement Dispatch in a React Native project?

Context App.tsx import React, { createContext, useContext, useReducer, useEffect, ReactNode, Dispatch, } from "react"; import AsyncStorage from "@react-native-async-storage/async-storage"; import { StateType, ActionType } f ...

What is the process of substituting types in typescript?

Imagine I have the following: type Person = { name: string hobbies: Array<string> } and then this: const people: Array<Person> = [{name: "rich", age: 28}] How can I add an age AND replace hobbies with a different type (Array< ...

Merging an assortment of items based on specific criteria

I have the following TypeScript code snippet: interface Stop { code: string } interface FareZone { name: string; stops: Stop[]; } const outbound: FareZone[] = [{name: 'Zone A', stops: [{ code: 'C00'}] }, {name: 'Zone B ...

What could be causing the error message "Error: Failed to retrieve component for route: '/settings'" to occur in next js?

In my Next.js index file, I have incorporated the Next-Auth version 4 library. import React from 'react' import { useRouter } from 'next/router' import { useSession } from 'next-auth/react' import { Login } from '@/compon ...

Is it possible to utilize a function within an Angular [routerLink] to define the query parameter?

When receiving a response from the API without an ID, it presents data fields like url, name, gender, culture, etc. However, I need to create a route to access specific character information using /characters/:id. Since there is no direct ID provided in th ...

NextJS: Build error - TypeScript package not detected

I'm facing an issue while setting up my NextJS application in TypeScript on my hosting server. On my local machine, everything works fine when I run next build. However, on the server, I'm encountering this error: > next build It seems that T ...

RXJS - Hold off until the shop is fully stocked

Here's a function I have that needs some adjustment: combineLatest([this.contact$, this.account$]).pipe( map((res) => {contacts = res[0], account = res[1]})).subscribe() I am facing an issue where the contact$ selector is sometimes empty. If it ...

How can I utilize a filter or pipe to populate product categories onto screens within Ionic 2?

I am considering creating an Ionic 2 app with 6 pages, but I'm unsure whether to utilize a Pipe or a Filter for the individual category pages and how to implement the necessary code. Each category page should be able to display products from the "app ...

Is it planned to include StencilJS as a development choice in Ionic?

I'm curious about the potential adoption of Stencil JS for developing mobile apps within the Ionic framework. When I mention "an option for developing," I'm referring to frameworks like NativeScript where developers can choose between Angular + ...

The transition from true to false occurs in router.isFallback

Here are the specifications for my current environment: Environment Version Rails 7.0.0 React 18.0 Next.js 12.1.4 These are my settings for getStaticPaths and getStaticProps: export const getStaticPaths = async () => { const data = await ...

Using Regex to replace special characters in TypeScript

I need assistance in removing the characters "?" and "/" from my inner HTML string. Can you guide me on how to achieve this using regex? For example, I would like to replace "?" with a space in the following content. "Hello?How are you?<a href="http:/ ...