Next.js Discord

Discord Forum

getServerSideProps HOC Typing

Unanswered
Asian black bear posted this in #help-forum
Open in Discord
Avatar
Asian black bearOP
Hello everyone, I've been trying to create a HOC function for getServerSideProps for Auth Routes.
I want to:
- pass the session to the page and to the handler callback
- I want to extend the result of the handler to include the session as well
I'm using next-auth for the session handling.

import type { GetServerSidePropsContext, GetServerSidePropsResult } from "next";
import {
    type DefaultSession,
    type DefaultUser,
    type NextAuthOptions,
    type Session,
} from "next-auth";

export type GetServerSidePropsWithSession<Props> = (
    context: GetServerSidePropsContextWithSession
) => GetServerSidePropsResult<Props> | Promise<GetServerSidePropsResult<Props>>;

// Props extends object is probably not correct
export const withAuthSSR = <Props extends object>(
    handler?: GetServerSidePropsWithSession<Props>,
    returnTo?: string
) => {
    return async (
        context: GetServerSidePropsContextWithSession
// GetServerSidePropsResult<Props & { session: Session }> is also probably not correct either
    ): Promise<GetServerSidePropsResult<Props & { session: Session }>> => {
        const session = await getServerAuthSession(context);

        if (session === null) {
            return {
                redirect: {
                    destination: `/auth/login&callbackUrl=${encodeURIComponent(
                        returnTo ?? context.resolvedUrl
                    )}`,
                    permanent: false,
                },
            };
        }

        if(handler === undefined)
            return {
                props: {
                    session // Typescript is complaining about this
                }
            }

        const ret = await handler(context);
        
        if("props" in ret) 
            return {
                ...ret,
                props: {
                    ...(await ret.props),
                    session
                }
            }
        else
            return ret;
    };
};

1 Reply

Avatar
Asian black bearOP
Maybe im just overcomplicating things, if so, what should i be doing instead?