Encountering ECONNREFUSED error when making requests to an external API in a NextJS application integrated with Auth

Currently, I have integrated Auth0 authentication into my NextJS application by following their documentation. Now, I am in the process of calling an external ExpressJS application using the guidelines provided here: https://github.com/auth0/nextjs-auth0/blob/main/EXAMPLES.md#access-an-external-api-from-an-api-route.

The setup involves running NextJS on port 3000 and Express on port 3001. My Express server configuration is as follows:

const jwtCheck = expressjwt({
    secret: jwksRsa.expressJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: process.env.AUTH0_JWKS_URI as string,
    }) as GetVerificationKey,

    audience: process.env.AUTH0_AUDIENCE as string,
    issuer: process.env.AUTH0_ISSUER as string,
    algorithms: ['RS256'],
})

app.use(jwtCheck)

While attempting to make an unauthenticated request from my NextJS app to the external API, I receive the

UnauthorizedError: No authorization token was found error
, which indicates that the authentication process is functioning correctly. If I comment out the app.use(jwtCheck), the requests are successful since there is no authentication check.

Here's how I have configured my NextJS application:

// [...auth0].ts


import { handleAuth, handleLogin } from '@auth0/nextjs-auth0'

export default handleAuth({
    login: handleLogin({
        authorizationParams: {
            audience: process.env.AUTH0_AUDIENCE, 
            scope: 'openid profile email read:trips',
        },
    }),
})


// /api/trips.ts

import { getAccessToken, withApiAuthRequired } from '@auth0/nextjs-auth0'

const apiURL = process.env.NEXT_PUBLIC_SERVER_URL

export default withApiAuthRequired(async function trips(req, res) {

    const { accessToken } = await getAccessToken(req, res, {
        scopes: ['read:trips'],
    })

    const response = await fetch(`${apiURL}/trips`, {
        headers: {
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
            Accept: 'application/json',
            Authorization: `Bearer ${accessToken}`,
        },
    })

    const trips = await response.json()
    res.status(200).json(trips)
})

// /pages/trips/index.tsx

const TripsPage = (props: InferGetServerSidePropsType<typeof getServerSideProps>) => {
    if (!props.user) return <div>User error!</div>


    return (
        <div>
            // components that use the fetched data
        </div>
    )
}


export const getServerSideProps = withPageAuthRequired({
    async getServerSideProps() {

        const { data } = await axios.get('/api/trips')

        try {
            return {
                props: {
                    data: data,
                },
            }
        } catch (e) {
            return {
                notFound: true,
            }
        }
    },
})

export default TripsPage

However, when trying to access the http://localhost:3000/trips page after logging in, I encounter an error:

GET http://localhost:3000/trips 500 (Internal Server Error)
Uncaught Error: connect ECONNREFUSED ::1:80
    at <unknown> (Error: connect ECONNREFUSED ::1:80)
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1487:16)

It appears that the request does not leave my NextJS application's domain. The internal API call seems to be failing. However, when directly accessing http://localhost:3000/api/trips, I do receive a response with JSON data and the logged access token indicates proper authentication. So, the issue lies with the actual page calling the NextJS proxy API, which communicates with my ExpressJS API.

The complete error log in the NextJS console can be viewed here:

https://i.sstatic.net/TT9gy.png

error - AxiosError: connect ECONNREFUSED ::1:80
    at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1487:16) {
  port: 80,
  address: '::1',
  .....

Any insights on what might be causing this issue?

Answer №1

Switching to 127.0.0.1 from using localhost solved my problem as well.

Answer №2

The problem arose due to restrictions on calling an internal NextJS /api/ route within the getServerSideProps method. Instead, we must make direct calls to external APIs without going through the internal /api proxy.

For more details, check out: https://github.com/auth0/nextjs-auth0/issues/995

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

"Retrieving Data Using jQuery's .ajax Method in Visual Basic

<WebMethod()> Public Shared Function gtet() As String ... Dim GET = uClass.GetSets(dbuser, dbparam1) ... End Function and $(document).ready(function () { data = { }; var jsondata = $.toJSON(data); $.ajax({ type: "GET ...

Tips for Dynamically Binding Data in Angular ChartsWant to learn how to dynamically bind

I have integrated angular-charts directives into my application and everything works perfectly when initializing the data. However, I encountered an issue when reading the data from a JSON file and assigning it to the chart. The x-axis and y-axis are gener ...

Setting the root position of a div: How can it be done?

Imagine a scenario where a div element is designed to follow the mouse cursor on the screen. This functionality is achieved by manipulating the document's `mousemove` event and adjusting the div's `left` and `top` positions based on the event dat ...

What is the best way to implement useRouter in Next.js version 14?

When I utilize router = useRouter() and then try to redirect with router.push('auth/new-password') from the path 'auth/login/approve', I unexpectedly end up being routed to 'auth/login/auth/new-password'. Can someone explain t ...

The removal of classList.remove() only eliminates the class itself, not its contents

My goal is to add one class and remove another class when the start quiz button is clicked. While the 'info_box' class is successfully added, the 'start_btn' class does not get removed; it just changes position (from flex to no flex). T ...

Cypress and Cucumber synergy: Experience automatic page reloads in Cypress with each test scenario in the Describe block

Hey, I'm facing an unusual issue. I have a dialog window with a data-cy attribute added to it. In my cucumber scenarios, I have one like this: Scenario: Users open dialog window When the user clicks on the open dialog button I've written Cypre ...

The most effective method for adding data to a <pre /> element is through VueJS

I have an electron app that executes a program and stores the output when data is received. My goal is to showcase the content of this output within an html pre element. One approach I can take is to create a variable and continuously add the output data ...

Styling the "Browse" button for different web browsers

Here is the code snippet I am working with: HTML: <form> <input id = "file" type="file" /> <div id="custom_button">custom button</div> </form> Jquery: $("#custom_button").on("click", function () { $("#file"). ...

Using Three.JS 'OrbitControls' in VueJS application results in a black screen appearing?

Currently, I've been delving into the basic cube exercise on Three.js, and incorporating the three.js cube into my Vue.JS application. Initially, everything was functioning smoothly, with my cube rotating as intended using animate, etc. However, thi ...

Ways to retrieve JSON information and incorporate it into an if statement in this specific scenario

Here is the AJAX function code I have written: $('#request_form').submit(function(e) { var form = $(this); var formdata = false; if (window.FormData) { formdata = new FormData(form[0]); } var formAction = form.attr( ...

Experiencing difficulty with parsing an array's json/string version within an Angular controller

Updated question for clearer understanding! I'm currently working on an Angular-Rails application and facing challenges when it comes to parsing an array. One of my ActiveRecord models has an attribute that is an array. Before reaching my Angular app ...

Automatically unset session variable 'unsetted' using a simple line of code

Why does the session information not get saved? When I reload the page, the session variable 'mucciusersess' disappears. What could be causing this issue? Thanks... I have a cookie on the client-side with a value like 'mucciuserid' se ...

Decode JSON and generate a user-friendly Array

My aim is to extract and organize the JSON data received from an external API into a custom array. However, I am encountering two challenges: I'm struggling to access the value labeled #2 under "Meta Data". If I want to extract the first array n ...

Trouble getting Fontawesome icons to accept color props when using react functional components with tailwindcss

Issue I'm Facing I'm currently working on a project that involves using icons extensively. Instead of manually adding a Fontawesome icon in every script, I have created a functional component that handles the rendering of icons based on given pr ...

Exclude extraneous keys from union type definition

Working on a call interface that outlines its arguments using specific properties and combined variants. type P1 = {prop1: number} type P2 = {prop2: number} type U1 = {u1: string} type U2 = {u2: number} export type Args = P1 & P2 & (U1 | U2) In th ...

How to use jQuery to dynamically set the value of a column span in a

Struggling with setting the value for a table column span. Here is my jQuery code: $('tr td data-th=Name span').val('My span content...'); This is how my HTML appears: <tr> <td data-th="Name"><span class="edit-inpu ...

Choose a procedure to reset to the original setting

I'm attempting to achieve something that seems straightforward, but I'm having trouble finding a solution. I have a <select> tag with 5 <option> elements. All I want to do is, when I click a button (which has a function inside of it), ...

Encountering an error message saying "assignment to undeclared variable"

I'm attempting to incorporate a react icon picker from material-ui-icon-picker However, I keep encountering an error stating "assignment to undeclared variable showPickedIcon" edit( { attributes, className, focus, setAttributes, setFocus, setState ...

Learn how to properly register the order of checkboxes in AngularJS

I have a unique requirement for my webapp where I need to display the order in which checkboxes are checked. I came up with the following code to achieve this functionality: $scope.updateNumbers = function(id, checked, inputs) { if (checked === true) ...

Store the Ajax response in localStorage and convert it into an object for easy retrieval and manipulation

I'm currently working on an Ajax request that retrieves JSON data from the server and then stores it in localStorage for use in my application. However, I feel like my current code may not be the most efficient way to accomplish this task, as I have t ...