Issue
I'm using NextAuth on a NextJs project and I'm getting the error "Type error: Property 'session' does not exist on type '{}'."
. I'm adding the session
property to my _app.tsx as suggested here:
https://next-auth.js.org/getting-started/example
I've also added that property to my custom MyApp
type interface but I still get the error. Follow my code:
import { NextComponentType } from "next";
import { Session } from "next-auth";
export interface CustomAppProps extends AppProps {
Component: NextComponentType & { auth?: boolean; session?: Session };
}
function MyApp({ Component, pageProps: { session, ...pageProps } }: CustomAppProps) {
//...
});
How can I fix it? Thanks!
Edit #1 (adding MyApp
with my current code):
function MyApp({ Component, pageProps: { session, ...pageProps } }: CustomAppProps) {
return (
<>
<CookieConsentProvider useCookieConsentHooksOptions={{ consentCookieAttributes: { expires: 360 } }}>
<SessionProvider session={session}>
<AppContextProvider>
<Component {...pageProps} />
</AppContextProvider>
</SessionProvider>
</CookieConsentProvider>
</>
);
}
Edit #2:
function MyApp({ Component, pageProps }: AppProps) {
return (
<>
<CookieConsentProvider useCookieConsentHooksOptions={{ consentCookieAttributes: { expires: 360 } }}>
<SessionProvider session={pageProps.session}>
<AppContextProvider>
<Component {...pageProps} />
</AppContextProvider>
</SessionProvider>
</CookieConsentProvider>
</>
);
}
Using the code above I still get the TS error:
Solution
I managed to fix that error by adding a custom type file to my project, as I saw on NexthAuth.js Github repository: https://github.com/nextauthjs/next-auth-typescript-example/blob/main/types/next.d.ts.
import type { NextComponentType, NextPageContext } from "next"
import type { Session } from "next-auth"
import type { Router } from "next/router"
declare module "next/app" {
type AppProps<P = Record<string, unknown>> = {
Component: NextComponentType<NextPageContext, any, P>
router: Router
__N_SSG?: boolean
__N_SSP?: boolean
pageProps: P & {
/** Initial session passed in from `getServerSideProps` or `getInitialProps` */
session?: Session
}
}
}
Just copied that to my project and that works now. Not sure why it used to work as I never had it before.
Answered By - Alexandre Paiva
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.