4

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?

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.