Having trouble with Next.js and Next-auth? When I make an HTTP request in getServerSideProps, getSession is returning null in my secured API Route

I am currently working on securing an API Route that is being called from both the Client and Server-side on different pages.

When accessing the test page, it returns a 401 error.

However, when accessing the test2 page, the content is retrieved successfully.

I suspect that the issue lies in passing the session when making the HTTP request in the getServerSideProps.

My main concern is how can I properly secure the API routes used on both the client and server sides?

/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) => {
        // retrieves session data
        const session = await getSession(context);

        // handles errors
        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;

    

Answer №1

I stumbled upon a resolution.

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;

Answer №2

When dealing with requests from serverSideProps, it is recommended to use a specific method instead of relying on useSession, which is designed for client requests.

Check out the documentation here for more information

The preferable approach is to utilize unstable_getServerSession as shown in the example provided in the documentation.

await unstable_getServerSession(req, res, authOptions)

Make sure to export authOptions from your [...nextauth].js file

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble displaying real-time camera RTSP streaming using Angular

I am currently in the process of developing a web application using Angular and I need to incorporate a window that displays live RTSP streaming. Upon conducting research, I discovered that this can be achieved by utilizing the JSMpeg JavaScript library. ...

What is the best way to transfer data to a different page in NextJS?

I need a solution for transferring data from my /app/mypage/ page to a new tab where /app/mypage/edit is loaded. The goal is to avoid reloading the data and instead pass it directly. The data object being transferred is quite large, so an efficient metho ...

Step-by-step guide on resolving AngularJS Issue: [$injector:modulerr]

I'm encountering an issue with Angular JS where I'm receiving the following error: jquery.js:7993 Uncaught Error: [$injector:modulerr] Failed to instantiate module application due to: Error: [$injector:nomod] Module 'application' is no ...

Utilizing variables as identifiers in React Native programming

Trying to utilize a dynamic name for a property of an object. For instance, within the function provided below, aiming to use the value stored in the variable 'catagoryId' to access the corresponding child element and assign it to the variable c ...

Overflow-y SweetAlert Icon

Struggling with a website modification issue where using Swal.fire(...) causes an overflow problem affecting the icon rendering. How can this be fixed? Here is the custom CSS code in question: * { margin: 0px; padding: 0px; font-family: &ap ...

Error in Typescript: The type 'Element' does not have a property named 'contains'

Hey there, I'm currently listening for a focus event on an HTML dialog and attempting to validate if the currently focused element is part of my "dialog" class. Check out the code snippet below: $(document).ready(() => { document.addEventListe ...

Utilizing Angular2 to access NPM package (Googleapis)

I am currently developing an Angular2 application that utilizes Webpack for the build process. I want to implement a Google oauth login feature in my application, so I have added the googleapi package from npm. However, I am facing difficulties when trying ...

Adjust the color scheme of the menu to match the newly updated background image

On the homepage, there is a background slideshow playing. The issue arises when the menu becomes invisible against a dark background due to its dark font color. It would be ideal for the menu's color to dynamically change with the background. I' ...

Tips for sending a JavaScript variable through an AJAX URL

I currently have a variable defined like this: var myip; I need to include this variable in the following URL: $.ajax('http://api.ipstack.com/**[myip]**?access_key=mykey') Manually replacing [myip] with my IP address works fine, but I am loo ...

Having trouble with res.redirect not working after the page has been rendered with data?

I have a basic forget password feature set up, where users can request a password change and receive an email with a token. Clicking the link in the email will redirect them to a page where they can input their new password. When I click on the email link ...

Jasmine - effectively mimicking an object that utilizes a constructor

Currently, I am attempting to simulate the native WebSocket in a jasmine test for Angular. I have successfully spied on the constructor and `send` function, but I am struggling to figure out how to fake a call of `onmessage`. The WebSocket has been extrac ...

What are the benefits of implementing a hexadecimal strategy in javascript?

I have a somewhat unusual question that has been puzzling me. I've noticed some interesting choices in naming variables in JavaScript, seemingly using what appears to be "a hexadecimal approach". For example, I see variables named like _0x2f8b, _0xcb6 ...

Issue with PHP causing Jquery alert to trigger twice rather than once

I am currently working with jQuery and PHP. I have a button labeled "Edit" but whenever I click on it, the alert message pops up twice instead of just once. Below is my HTML code within the PHP tags: <?php $PostComment2='<div class="button1 ...

Exploring the depths of Next.js and ASP.NET Core Web API with the challenge of DEPTH_ZERO_SELF_SIGNED_CERT

My current setup involves utilizing Asp.net Core Web API as the backend and Next.js as the frontend. The API is running on localhost with a self-signed SSL, making it accessible through https. On the other hand, Next.js runs on localhost without SSL, only ...

Find and return a specific record from MongoDB if it matches the exact value

model.js import mongoose from 'mongoose'; const { Schema, Types } = mongoose; const participants = { user_id: Types.ObjectId(), isAdmin: Boolean } const groupSchema = new Schema({ id: Types.ObjectId(), // String is shorthand for {type: St ...

Challenge with row identification in Datatables when rowId begins with a number

In compliance with the Datatables specifications, each row in my table can be assigned a unique ID: $('#myTable').DataTable( { ajax: '/api/staff', rowId: 'staffId' } ); However, it is mentioned in the same specificat ...

Express.static is having difficulty serving the JSON file

I have a series of inquiries: Currently, I am in the process of developing an application using Angular and Node (Express). 1) Within my Node server, I am serving all static files from my 'static_dir' app.use(express.static(STATIC_DIR)); Insi ...

Saving the state of checkboxes in Angular Material

I am trying to figure out a solution for storing checkbox values, specifically whether they have been checked before or not. For example, I have this dialog: After clicking on a checkbox and then clicking Save, the checkboxes reset to being unchecked when ...

The npm error message states: "Unable to locate the 'readable-stream' module."

Recently, I installed node js on my Windows 10 machine with version v4.4.2. However, whenever I attempt to run npm install or check npm version, it throws the following error message. Any assistance on this matter would be highly appreciated. Error: Canno ...

How come useEffect runs only once even when multiple states in the dependency array of useEffect change simultaneously?

<div onClick={() => { updateValue1((x: number) => x + 1); updateValue2((x: number) => x + 3); }} > one? two? </div> const [value1, updateValue1] = useState(1); const [value2, updateValue2] = useState(1 ...