Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

258
Views
next.js & next-auth When I send http request in getServerSideProps, getSession returns null in secured API Route

I am trying to secure the API Route and this API route is called in the Client and Server-side on different pages.

On the test page, it returns 401 error.

On the test2 page, it returns the content well.

I guess it doesn't pass session when I send the http request in the getServerSideProps.

My question is, how do I secure the API routes used on the client and server-side?

/pages/test

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;

/pages/test2

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;

/pages/api/secret

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 answers
Answer question

0

I found a solution.

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

/pages/api/secret

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!