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

261
Vistas
next.js & next-auth Cuando envío una solicitud http en getServerSideProps, getSession devuelve un valor nulo en la ruta API segura

Estoy tratando de asegurar la ruta API y esta ruta API se llama en el lado del cliente y del servidor en diferentes páginas.

En la página de test , devuelve 401 error .

En la página test2 , devuelve bien el contenido.

Supongo que no pasa session cuando envío la solicitud http en getServerSideProps .

Mi pregunta es, ¿cómo aseguro las rutas API utilizadas en el lado del cliente y del servidor?

/páginas/prueba

 import React from 'react'; import axios from 'axios'; import { getSession } from 'next-auth/react'; const Test = (props) => { return <div>test</div>; }; export const getServerSideProps = async (context) => { // it returns session data const session = await getSession(context); // it returns error const res = await axios.get('/api/secret'); return { props: { session, secret: res.data, }, }; }; export default Test;

/páginas/prueba2

 import React, { useEffect } from 'react'; import axios from 'axios'; import { useSession, getSession } from 'next-auth/react'; const Test = (props) => { const { data: session } = useSession(); useEffect(() => { const fetchData = async () => { const res = await axios.get('/api/secret'); console.log(res.data); }; fetchData(); }, [session]); return <div>test</div>; }; export default Test;

/páginas/api/secreto

 import { getSession } from 'next-auth/react'; const handler = (req, res) => { const { method } = req; switch (method) { case 'GET': return getSomething(req, res); default: return res.status(405).json('Method not allowed'); } }; const getSomething = async (req, res) => { const session = await getSession({ req }); console.log(session); if (session) { res.send({ content: 'Welcome to the secret page', }); } else { res.status(401).send({ err: 'You need to be signed in.', }); } }; export default handler;
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Encontré una solución.

 export const getServerSideProps = async (ctx) => { const session = await getSession(ctx); const headers = ctx.req.headers; if (session) { const data = ( await axios.get(`${process.env.NEXTAUTH_URL}/api/secret`, { headers: { Cookie: headers.cookie }, }) return { props: { data, }, }; } else { return { redirect: { destination: '/login', permanent: false, }, }; } };

/páginas/api/secreto

 import { getSession } from 'next-auth/react'; const handler = async (req, res) => { const { method } = req; switch (method) { case 'GET': return await getSomething(req, res); default: return res.status(405).json('Method not allowed'); } }; const getSomething = async (req, res) => { const session = await getSession({ req }); // console.log(session); if (session) { res.send({ content: 'Welcome to the secret page', }); } else { res.status(401).send({ err: 'You need to be signed in.', }); } }; export default handler;
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