Estoy tratando de seguir la documentación de autenticación siguiente usando TypeScript. Usando el siguiente código y algún código en _app.tsx de los documentos, puedo proteger una página:
AdminDashboard.auth = { role: "admin", loading: <AdminLoadingSkeleton />, unauthorized: "/login-with-different-user", // redirect to this url }¿Cuál es la forma correcta de implementar esto usando TypeScript?
Encontré una solución que funciona, pero no estoy seguro de si esta es la forma correcta:
export type NextPageWithAuth = NextPage & { auth: boolean, role: string } type NextPageAuthProps = { Component: NextPageWithAuth, pageProps: any } El tipo AppProps es bastante más sofisticado que mi propio NextPageAuthProps .
En la página, puede ampliar el tipo integrado de NextPage para incluir el campo de auth con el tipo adecuado.
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; Luego, en la _app personalizada, puede extender AppProps para que Component prop extienda el tipo que declaró en la página.
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) { //... }