Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

168
Vistas
¿Cómo obtener el objeto de usuario Auth0 en getServerSideProps?

Estoy tratando de usar Auth0 con NextJS para la autenticación de usuarios. Después de iniciar sesión, quiero acceder al objeto de usuario en getServerSideProps. Seguí este enlace a continuación,

Sin embargo, Stackoverflow , cuando intento pegar el código, se muestra un error de mecanografiado. He adjuntado el código y el error a continuación. Por favor, hágame saber cómo se puede resolver esto.

 import { withPageAuthRequired } from '@auth0/nextjs-auth0'; export default withPageAuthRequired(function Profile({ user, newData }) { return ( <> <div>{user.name}</div> </> ) }); export const getServerSideProps = withPageAuthRequired({ async getServerSideProps (context){ return { props: { newData: "user" } } } });

código de error:

 { "resource": "/Users/username/Downloads/proj/projectname/pages/profile.tsx", "owner": "typescript", "code": "2345", "severity": 8, "message": "Argument of type '{ getServerSideProps(context: any): Promise<{ props: { newData: string; }; }>; }' is not assignable to parameter of type 'ComponentType<WithPageAuthRequiredProps>'.\n Object literal may only specify known properties, and 'getServerSideProps' does not exist in type 'ComponentType<WithPageAuthRequiredProps>'.", "source": "ts", "startLineNumber": 73, "startColumn": 11, "endLineNumber": 73, "endColumn": 29 }

Captura de pantalla: ingrese la descripción de la imagen aquí

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Tienes un ejemplo aquí.

Basado en tu ejemplo:

 import { getSession, withPageAuthRequired } from '@auth0/nextjs-auth0'; export default function ProtectedPage({user}) { return ( <> <div>{user.name}</div> </> ) }); export const getServerSideProps = withPageAuthRequired({ //returnTo: '/foo', async getServerSideProps(ctx) { const session = getSession(ctx.req, ctx.res); //check the console of backend, you will get tokens here console.log(session); return {props: { customProp: 'bar' }}; } });

Observe la diferencia entre getSession y {user} : puede definir algunas acciones como "redireccionar a" en getServerSideProps . ¿Qué significa? Significa que puede, por ejemplo, redirigir a los usuarios sin acceso a una página personalizada, por ejemplo, 404

PD: no tiene context , necesita tener la variable ctx

about 4 years ago · Juan Pablo Isaza Denunciar

0

Solo necesita envolver getServerSideProps . Aquí hay un ejemplo que funcionó para mí:

 import React, { ReactElement } from 'react'; import { getSession, withPageAuthRequired } from '@auth0/nextjs-auth0'; import db from '.'; interface Props { user: DbUser; // Not the auth0 user } export default function Profile({ dbUser }: Props) { return <div>{JSON.stringify(dbUser, null, 2)}</div>; }; export const getServerSideProps = withPageAuthRequired({ getServerSideProps: async ({ req, res }) => { const auth0User = getSession(req, res); // Fetch the user from the db (by email) let user = await db.user.findUnique({ where: { email: auth0User?.user.email } }); // You might want to move the creation of the user somewhere else like afterCallback // Checkout https://auth0.github.io/nextjs-auth0/modules/handlers_callback.html if (!user) { user = db.user.create(auth0User?.user); } return { props: { dbUser: user, }, }; }, });
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda