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;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;