Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How define Next js Context types in Typescript?

I need to know how to define next js Context types and and it's req types?

Here I write this getServerSideProps function-

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

And here I write this function-

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

Here How Can I define context types and req types?

Please help me?

like image 300
Samia Sammi Avatar asked Oct 20 '25 12:10

Samia Sammi


1 Answers

In VS Code, you can right click on a type and click "Go to Definition". The type of GetServerSideProps is defined inside next.js as:

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>>

So it looks like the context parameter is a GetServerSidePropsContext, with some generic parameters.

Which means your function becomes:

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"]
) {
  // ...
}

I would just drop the req parameter though, it's already in context. Extract it inside getMovies if you must.

like image 122
MHebes Avatar answered Oct 23 '25 00:10

MHebes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!