ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Saturday, November 19, 2022

[FIXED] How to extend NextPage type to add custom field to page component?

 November 19, 2022     javascript, next.js, reactjs, typescript   

Issue

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.


Solution

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) {
   //...
}


Answered By - juliomalves
Answer Checked By - - Terry (ReactFix Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix