6

I am trying to follow the next-auth documentation using TypeScript. Using the following code and some code in _app.tsx from the docs I can protect a page:

AdminDashboard.auth = {
  role: "admin",
  loading: <AdminLoadingSkeleton />,
  unauthorized: "/login-with-different-user", // redirect to this url
}

What is the right way to implement this using TypeScript?

I found a solution which works, but I am not sure if this is the right way:

export type NextPageWithAuth = NextPage & {
  auth: boolean,
  role: string
}

type NextPageAuthProps = {
  Component: NextPageWithAuth,
  pageProps: any
}

The AppProps type is quite more sophisticated than my own NextPageAuthProps.

2 Answers 2

13

In the page, you can extend the built-in NextPage type to include the auth field with the appropriate type.

import type { NextPage } from 'next';

type PageAuth = {
  role: string
  loading: JSX.Element
  unauthorized: string
};

export type NextPageWithAuth<P = {}, IP = P> = NextPage<P, IP> & {
  auth: PageAuth
};

const AdminDashboard: NextPageWithAuth = () => {
  // Your `AdminDashboard` code here
};

AdminDashboard.auth = {
  role: "admin",
  loading: <AdminLoadingSkeleton />,
  unauthorized: "/login-with-different-user"
};

export default AdminDashboard;

Then, in the custom _app, you can extend AppProps so that the Component prop extends the type you declared in the page.

import type { NextComponentType, NextPageContext } from 'next';
import type { NextPageWithAuth } from '<path-to>/AdminDashboard';

type NextComponentWithAuth = NextComponentType<NextPageContext, any, {}> & Partial<NextPageWithAuth>

type ExtendedAppProps<P = {}> = AppProps<P> & {
  Component: NextComponentWithAuth
};

function MyApp({ Component, pageProps }: ExtendedAppProps) {
   //...
}
6
  • Can you please elaborate on the return statement that satisfies the type NextPageWithAuth.
    – petrosmm
    Feb 25, 2022 at 1:58
  • 1
    @petrosmm It's extending the existing NextPage type to also include an auth property. Feb 27, 2022 at 19:20
  • That part is clear, but, what would a sample return line look like for AdminDashboard ?
    – petrosmm
    Feb 28, 2022 at 16:27
  • 1
    @petrosmm That would be like any other React component. The additional typing just allows to then have AdminDashboard.auth = { ... } set on that component, without TypeScript complaining. Feb 28, 2022 at 16:31
  • 1
    Oh wow, worked, thank you. That was so simple -- still learning here. It seemed like an object initializer usage that maybe I was not familiar with. Upvote!
    – petrosmm
    Feb 28, 2022 at 17:47
0

The accepted answer's type definitions hurt my head, so I solved the issue by calling getStaticProps with an auth property on the pages I wanted to protect:

// bottom of page I want to protect..

export const getStaticProps = async () => {
  return {
    props: { auth: true },
  };
};

and then consuming the prop in _app.tsx like so:

const MyApp: AppType<{ session: Session | null, auth: boolean }> = ({
  Component,
  pageProps: { session, ...pageProps },
}) => {

  const { auth } = pageProps

  return (
    <SessionProvider session={session} refetchOnWindowFocus={false}>
      <NavBar />
      {auth ? (
        <RouteGuard>
          <Component {...pageProps} />
        </RouteGuard>
      ) : (
        <Component {...pageProps} />  
      )}
      <ReactQueryDevtools />
      <MobileFooter />
    </SessionProvider>
  );
};

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.