What is the best way to specify Next.js Context types in TypeScript?

Can someone help me with defining the types for next js Context and req?

Below is the code for the getServerSideProps function-

//Server side functions
export const getServerSideProps: GetServerSideProps = async (context) => {
    await getMovies(context, context.req);
    return { props: {} }
}

As well as the function-

export const getMovies = (context: **types, req: **types) => {
    //here the main function
}

Could someone guide me on how to define the types for context and req?

Any help would be appreciated. Thank you.

Answer №1

If you're using VS Code, you have the option to simply right click on a type and select "Go to Definition". The definition for the GetServerSideProps type is specified within next.js as follows:

export type GetServerSideProps<
  P extends { [key: string]: any } = { [key: string]: any },
  Q extends ParsedUrlQuery = ParsedUrlQuery,
  D extends PreviewData = PreviewData
> = (
  context: GetServerSidePropsContext<Q, D>
) => Promise<GetServerSidePropsResult<P>>

From this, it is evident that the context parameter is of type GetServerSidePropsContext, with certain generic parameters.

Therefore, your function can be modified as shown below:

import type {
  GetServerSideProps,
  GetServerSidePropsContext,
  PreviewData,
} from "next";
import { ParsedUrlQuery } from "querystring";

// ...

export function getMovies<Q extends ParsedUrlQuery, D extends PreviewData>(
  context: GetServerSidePropsContext<Q, D>,
  req: GetServerSidePropsContext<Q, D>["req"]
) {
  // ...
}

Consider omitting the req parameter, as it is already included in the context. If necessary, you can extract it within the getMovies function.

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

How do I specify TypeScript types for function parameters?

I've created a function and used TypeScript to define parameter types: const handleLogin = async ( e: React.FormEvent<EventTarget>, navigate: NavigateFunction, link: string, data: LoginDataType, setError: React.Dispatch<Re ...

How to host two Node.js socket.io projects on one URL

My Nodejs server is hosted on Amazon Lightsail. I have successfully connected to it and configured Apache for Nodejs. I am working with 2 Nodejs socket.io projects and I want to access both of them using a single URL. Below are the links in Nextjs: const ...

Stop receiving updates from an Observable generated by the of method

After I finish creating an observable, I make sure to unsubscribe from it immediately. const data$ = this.httpClient.get('https://jsonplaceholder.typicode.com/todos/1').subscribe(res => { console.log('live', res); data$.unsubscr ...

Exploring server-side rendering authentication in a fresh application folder with Next.js version 13

Since transitioning to the new app directory a couple of weeks ago, I've been navigating through different issues and trying to find my way around. I have a server function set up to retrieve the current user's details by using an authorization ...

Need help incorporating metadata in the `not-found.tsx` file within NextJS?

Within my NextJS application, I have a file called not-found.tsx containing basic metadata in the main directory of my app: import { Metadata } from "next"; export const metadata: Metadata = { title: "Page not found", }; export defa ...

Versatile Typescript options

Is it possible to enforce a value to be within a list using TypeScript with enums? Can this be achieved with TypeScript type definitions? enum Friend { JOHN, SALLY, PAUL, } type MyFriends = { friends: Friend[], bestFriend: <> //How ca ...

Having trouble resolving 'primeng/components/utils/ObjectUtils'?

I recently upgraded my project from Angular 4 to Angular 6 and everything was running smoothly on localhost. However, during the AOT-build process, I encountered the following error: ERROR in ./aot/app/home/accountant/customercost-form.component.ngfactory. ...

Why can't I retrieve a token from the cookies?

After a user logs in, the application sends a request to the backend implemented with Next.js. Next.js sets cookies using res.Header(...) and then responds back to the front-end. However, I am having trouble retrieving the cookies-token from the response, ...

rxjs - monitoring several observables and triggering a response upon any alteration

Is there a way to watch multiple observables and execute a function whenever any of them change? I am looking for a solution similar to the functionality of zip, but without requiring every observable to update its value. Also, forkJoin isn't suitable ...

No matter what I attempt, Ng-options is still failing to work properly

This is my custom selection element: <select ng-options="country.country for country in countries" formControlName="country"></select></label> Below is the TypeScript component code associated with it: import { Component } from ' ...

Attribute specified does not belong to type 'DetailedHTMLProps<ButtonHTMLAttributes

I am working on creating a reusable 'button' component and I would like to include a href attribute so that when the button is clicked, it navigates to another page. An Issue Occurred: The following error was encountered: 'The type '{ ...

What is the best way to implement a search feature in my Next.js application that integrates with Supabase?

Hey there! I have a database filled with people's information and I really need to add a search feature to my web app so users can easily find what they're looking for. I attempted to implement the Full Text Search functionality, as outlined in ...

Having trouble verifying exceptions in TypeScript/Node.js using Chai

I am facing an issue while trying to test a simple function using chai assertion in my TypeScript code. Here is the function I have: public async test1(){ throw (new Error(COUCH_CONNECTION_ERROR.message)); } The definition of COUCH_CONNECTION_ERROR ...

Determining the output type by considering the presence of optional parameters

function customFunction<T>(defaultValue?: T) { return defaultValue; } const definitelyNullOrUndefined = customFunction<string>(); // type: string | undefined const definitelyStringType = customFunction<string>('foobar'); // ...

Is there a way to check if a date of birth is valid using Regular Expression (RegExp) within a react form?

const dateRegex = new RegExp('/^(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.] (19|20)\d\d+$/') if (!formData.dob || !dateRegex.test(formData.dob)) { formErrors.dob = "date of birth is required" ...

Invoke an ActionCreator within a different ActionCreator

Calling an ActionCreator from another file is proving to be a challenge... The products.ts file contains the ActionCreators and Reducers for Products... import { setStock } from './Store.ts'; //.... export const addProduct = (product: IProduct) ...

Error code -8 occurred while executing the yarn dev command, unable to identify the issue

I'm facing an issue with my development script that is structured like this: "scripts": { "dev": "./test.sh", }, Upon running the 'yarn dev' command, I encounter the following error message: Internal Error: ...

The error "ReferenceError: window is not defined" occurs when calling client.join() due to

I am looking to create a video call application using React and Next.js with the AgoraRTC SDK. After successfully running AgoraRTC.createClient(), AgoraRTC.createStream(), and client.init(), I encountered an error when trying to execute client.join(). The ...

How to retrieve an imported tag from an array in React programming

There is an issue with displaying a tag that is imported into an array. {files[1]} seems to be empty. To display the imported tag, I had to resort to using the standard declaration: <FileOne/> This was my attempted solution: const FileOne = ( () ...

Opt for Observable over Promise in your applications

I have implemented this function in one of my servlets: private setValues() { this.config.socket.on('config.weather', (values:any) => { console.log(values); } However, I would like to refactor it to something like this: private se ...