Search code examples
javascriptreactjstypescriptnext.jsnext-auth

Next.js (TypeScript) - Property 'req' does not exist on type 'GetServerSideProps'


I'm working with next-auth, and I am trying to access the session from getServerSideProps.

For that, I need to pass to it the context request and context response objects, but VScode shows a complaint that these properties don't exist on the context object.

This is where I see how to use next-auth in getServerSideProps. This is my code:

import React from "react";
import type { GetServerSideProps } from "next";
import { getServerSession } from "next-auth/next";
import { authOptions } from "../../pages/api/auth/[...nextauth]";

function EditProfile() {

  return (
    <>
    ....
    </>
  );
}

export async function getServerSideProps(context: GetServerSideProps) {
  
  const session = await getServerSession(context.req, context.res, authOptions);

  return {
    props: {},
  };
}

export default EditProfile;

And the complaints I get are:

Property 'req' does not exist on type 'GetServerSideProps<{ [key: string]: any; }, ParsedUrlQuery, PreviewData>'

And

Property 'res' does not exist on type 'GetServerSideProps<{ [key: string]: any; }, ParsedUrlQuery, PreviewData>'

Solution

  • Change your type declaration as below, because GetServerSideProps is the type of the function, meaning its parameter, context, and its return value.

    import { GetServerSideProps } from "next";
    
    export const getServerSideProps: GetServerSideProps = async (context) => {
      // ...
      return {
        props: {},
      };
    };
    

    You are getting those errors because you assumed it was the type of the parameter only.