500 Internal Server Error or 302 on Deployed Next.js App on Vercel When Sending Email After Auth, Works Locally

I’ve developed a Next.js application that sends an email to users after they sign in using NextAuth with a Google provider. The email sending functionality is implemented in an API route (api/email/route.js) and is triggered in the signIn callback of NextAuth. This setup works perfectly in my local environment. However, when deployed internally (not specified where), it only successfully sends emails when triggered via Postman. When a user signs in through the application, it fails and returns a 500 internal server error.

Here’s a simplified overview of my setup:

Email API Route (api/email/route.js):

Uses Axios to POST to an external email service.
Logs data and recipient email.
Sends a 202 status on success, or forwards the error status.
Email Utility Function (utils/sendEmail.js):

Calls the above API route.
Returns true regardless of email success (might need to revisit this logic).
NextAuth Configuration (api/auth/[…nextauth]/route.js):

After successful sign-in, it triggers the email utility function.
Logs response and continues regardless of email success.
Locally, this flow works without any issues. However, in the deployed environment, the email API route is returning a 500 error only when triggered through the sign-in process. Direct calls via Postman are successful.

// api/email/route.js
import axios from "axios";
import { NextRequest, NextResponse } from 'next/server';

export async function POST(request) {
  try {
    const data = await request.json();
    console.log("data", data);
    const recipientEmail = data.email;
    console.log("recipientEmail", recipientEmail);

    const response = await axios.post("https://api.getresponse.com/v3/contacts",
      {
        email: recipientEmail,
        campaign: {
          campaignId: `${process.env.GET_RESPONSE_CAMPAIGN_ID}`,
        },
      },
      {
        headers: {
          "X-Auth-Token": `api-key ${process.env.GET_RESPONSE_API_KEY}`,
        },
      }
    );

    if (response.status === 202) {
      return new NextResponse('Email sent successfully', { status: 202 });
    } else {
      return new NextResponse('Failed to send email', { status: response.status });
    }
  } catch (error) {
    console.error("Error sending email:", error);
    return new NextResponse('Internal Server Error', { status: 500 });
  }
}
// utils/sendEmail.js
const sendEmail = async (email) => {
  try {
    const response = await fetch(`${process.env.NEXT_PUBLIC_WEBSITE_URL}/api/email`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ email }),
    });
    console.log("response", response);
    if (!response.ok) throw new Error('Failed to send email');

    return true;
  } catch (error) {
    console.error('Error sending email:', error);
    // Decide if you want to return false or true based on email failure
    return true;
  }
}

export default sendEmail;

used it here in
api/auth/[…nextauth]/route.js so after successful sign in it does automatically and it works in local enviroment

import NextAuth from 'next-auth'
import GoogleProvider from 'next-auth/providers/google'

export const authOptions = {
  providers: [
    GoogleProvider({
      clientId: process.env.GOOGLE_CLIENT_ID,
      clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    }),
  ],
  callbacks: {
    async signIn({ user }) {
      if (user && user.email) {
        try {
          const response = await fetch(`${process.env.NEXT_PUBLIC_WEBSITE_URL}/api/email`, {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({ email: user.email }),
          });
          console.log("response", response);
          if (!response.ok) throw new Error('Failed to send email');
    
          return true;
        } catch (error) {
          console.error('Error sending email:', error);
          // Decide if you want to return false or true based on email failure
          return true;
        }
      }
      return true;
    }
  },
  theme: {
    colorScheme: "light", 
    brandColor: "#000000",
    logo: "", 
    buttonText: "Sign In"
  }
}

export const handler = NextAuth(authOptions);
export { handler as GET, handler as POST };

as well as in some components handling login

I’ve checked the following:

Environment variables are correctly set in the deployed environment.
The external email service works as expected (confirmed via Postman).
There are no apparent differences in the request payload between local and deployed environments.
I suspect the issue might be related to the Next.js serverless functions or some deployment-specific configuration, but I’m not sure what specifically could be causing this behavior.

Could anyone suggest what might be causing this discrepancy between the local and deployed environments? Are there any deployment-specific considerations for Next.js serverless functions that I might be missing?

What is the use of new keyword in Linked List and how to use it?

I am learning Linked List and get confused the use of that new keyword (new Node) in Linked List ? Is there any other method to avoid this “new” ? Also not understand the concept of new and this keyword, Also explain the syntax of new, I watched video and try this code in vs code and it ran successfully but the problem is i could not understand use of new here. And there is no article that helped me.

Node* convertArr2LL(vector<int> &arr){ Node* head = new Node(arr[0]); Node* mover = head;

Program where marker hits the border of 2d ArrayList and breaks out of loop

I would be grateful for help. The stimulation is supposed to represent a person walking around the island randomly for 50 turns and once the person hits either a ‘E’ or ‘D’, it breaks out of the loop cause they have either escaped or drowned. The person can go up, down, left, right randomly. If the person doesn’t hit the border within 50 turns, then the person has starved. There are also numbers around the island that indicate where the person has been and what number of turns they taken.

I figured out how to make the person move up, down, left, and right randomly, and how to mark the number of turns it has made throughout the island. How to make it so that when the person touches an “E” or “D” the loop will stop?

Also, when I try to generate the initial island, the output comes out like this (there are still zeros at the last column, when there should be ‘E’s there instead:

D D D D D D D D D D E D E D D
E 0 0 0 0 0 0 0 0 0 0 0 0 0 D
D 0 0 0 0 0 0 0 0 0 0 0 0 0 0
D 0 0 0 0 0 0 0 0 0 0 0 0 0 D
E 0 0 0 0 0 0 0 0 0 0 0 0 0 0
D 0 0 0 0 0 0 0 0 0 0 0 0 0 D
E 0 0 0 0 0 0 0 0 0 0 0 0 0 D
E 0 0 0 0 0 0 0 0 0 0 0 0 0 0
D 0 0 0 0 0 0 0 0 0 0 0 0 0 D
D E D D D D D D D D D D D E E

Here’s my code so far:

import java.util.ArrayList; 
import java.util.Random;

public class MIsland { 
final int PERCENT_BRIDGES = 30; 
private ArrayList<ArrayList<String>> island; 
ArrayList<ArrayList<String>> islandString = new ArrayList<>(); 
String decidingMark; 
private int moveCount; 
private int pRow; 
private int pCol; 
private Random generator;

public MIsland(Random generator) {
    this.generator = generator;
    island = new ArrayList<>();
    pRow = 5;
    pCol = 7;
    moveCount = 0;
    
    
    
    
}

public void initializingIsland() {
    
    //adding rows
    for (int i = 0; i <10; i++) {
        ArrayList<String> rowInIsland = new ArrayList<String>();
        for (int j=0; j < 15; j++) {
            rowInIsland.add("0");
        }
        island.add(rowInIsland);
    }
    

    
    for (int row = 0; row < 10; row++) {
        for(int col = 0; col <15; col++) {
            if (row == 0) {
                if (generator.nextInt(100) <= PERCENT_BRIDGES) {
                    island.get(0).set(col, "0"); //escape
                }
                else {
                    island.get(0).set(col ,"-1"); //drown 
                }
            }

}
}
            else if (row == 9) {
                if (generator.nextInt(100)+1 <= PERCENT_BRIDGES) {
                    island.get(9).set(col, "0"); //escape
                }
                else {
                    island.get(9).set(col ,"-1"); //drown 
                }
            }
        }
        
        
        
        if (generator.nextInt(100)+1 <= PERCENT_BRIDGES) {
            island.get(row).set(0,"0"); //escape
        }
        else {
            island.get(row).set(0,"-1"); //drown 
        }
        if (generator.nextInt(100)+1 <= PERCENT_BRIDGES) {
            island.get(row).set(14, "0"); //escape
        }
        else {
            island.get(row).set(14,"-1"); //drown 
        }
    }
            
                
}
        
    
    
public void setEsDs() {
    
    
    for (ArrayList<String> r : island ) {
        for (String value : r) {
            if (value.equals("0") && (island.indexOf(r) == 0 || island.indexOf(r) == 9)) {
                r.set(r.indexOf(value), "E");
            }
            else if (value.equals("-1")) {
                r.set(r.indexOf(value), "D");
            }
            
            if (value.equals("0") && (r.indexOf(value) == 0 || r.indexOf(value) == 14)) {
                r.set(r.indexOf(value), "E");
            }
        }
    }
    
}
    

public void placingPosition() {
    pRow = 4;
    pCol = 7;
    
    Random randall = new Random();
    
    //updating the mouse's position based on the moveDirection
    while (moveCount <= 50) {
            switch (generator.nextInt(4)+1) {
                case 1:
                    if (pRow > 0) {
                        pRow--;
                        
                    }
                    break;
                case 2:
                    if (pCol < 14) {
                        pCol++;
                    }
                    break;
                case 3:
                    if (pRow < 9) {
                        pRow++;
                    } 
                    break;
                case 4:
                    if (pCol > 0) {
                        pCol--;
                    }
                    break;
            }
            
            if ((pRow == 0 || pCol == 9) && (pCol == 0 || pCol== 14)) { 
                decidingMark = island.get(pRow).get(pCol);
                break;
            }
            else {
                moveCount++;
                island.get(pRow).set(pCol, Integer.toString(moveCount));
            }
        
            
        }
}
    

    

public void printIsland() {
    
    
    for (ArrayList<String> row : island) {
        for(String element : row) {
            
            System.out.print(element +" ");
        }
        System.out.println(); //Move to the next row
    }   
}

import java.util.Random;

public class MIslandTest {

    public static void main(String[] args) {
        Random rand = new Random();
        int starveCount = 0;
        int drownCount = 0;
        int escapeCount = 0;
        
        //for (int i = 0; i <100; i++) {
            
            MIsland island = new MIsland(rand);
            island.initializingIsland();
            
            
            island.setEsDs();
        
            //island.placingPosition();
            
                
            //if (i<3) {
                //System.out.println("Stimulation " + (i + 1));
                
                island.printIsland();
            }
        
        
        //}
        
        
        
    
    //}
}

`

Unable to resolve: Compiled /not-found error for Nextjs react project

I ran into this error on refresh of my project where upon “npm run dev” -> and reload of my site locally -> I see Compiled /not-found on my command line. And the site itself isnt loaded fully.

Also, none of the animated via framer motion elements are dislayed or animating).

The specific error I see on browser/console: Failed to load resource: the server responded with a status of 404 (Not Found)

I tried npm install and removing newly inserted packages
I also tried removing most recently added code and packages added to go back to ther era in which it was working
I updated my node version

Link to my repo:
https://github.com/elizzakai/new_portfolio

How to change btn-primary color for unchecked radio button?

Desired outcome:
I want to set background-color: #FFFFF when the radio button is unchecked and background-color: #9381FF when the radio button is checked.

Current outcome:
Both buttons render background color as #9381FF.

I know !important is not the best technique but I’m a beginner and having a hard time understanding the other options on this SO post, so I’ve resorted to trying to work through this strategy.

How do I get the unchecked radio button to have a white background?

Client code for radio

    <% layout('layouts/boilerplate') %>

    <div class="col-md-4 mb-3">
        <div class="btn-group" role="group" aria-label="Event Filter">
          <input type="radio" class="btn-check" name="eventFilter" id="upcomingEvents" value="upcoming" autocomplete="off" checked>
          <label class="btn btn-primary" for="upcomingEvents">Upcoming events</label>
          
          <input type="radio" class="btn-check" name="eventFilter" id="pastEvents" value="past" autocomplete="off">
          <label class="btn btn-primary" for="pastEvents">Past events</label>
        </div>
      </div>    

Css code

.btn-primary,
.btn-primary:active,
.btn-primary:visited,
.btn-primary:checked,
.btn-primary:focus {
    background-color: #9381FF !important;
    border-color: #9381FF !important;
    color: #e8f1f9 !important;
    border-radius: 2em;
}

.btn-primary:hover {
    background-color: #6f5cd9 !important;
    border-color: #6f5cd9 !important;
    color: #e8f1f9 !important;
    border-radius: 2em;
}

.btn-primary:not(:checked) {
    background-color: white; /* Change background to white when unchecked and hovered */
    border-color: #9381FF;
    color: #e8f1f9;
    border-radius: 2em;
}

FYI – my layouts/boilerplate file calls my app.css file after calling the bootstrap cdn (below):

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4"
    crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">

<script src='https://api.mapbox.com/mapbox-gl-js/v2.4.1/mapbox-gl.js'></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v2.4.1/mapbox-gl.css' rel='stylesheet' />
<link rel="stylesheet" href="/stylesheets/app.css">

Cheerio not outputting full element it grabs?

Put together a script to scrape a block of metadata from Realtor.com, based within a <script> tag with the ID "__NEXT_DATA__". However, when I tell Cheerio to pull it out, it returns a broken, truncated version that’s capped at 5000 characters and replaced much of the data with and ellipses (...).

import axios from "axios";
import cheerio from "cheerio";
import fs from "fs";

// set target URL
const url = "https://www.realtor.com/realestateandhomes-search/12345/type-townhome,single-family-home,condo,multi-family-home,mfd-mobile-home,farms-ranches.html";

// data scrape function
async function scrapeData() {
  try {
    // Fetch HTML of page
    const response = await axios.get(url, {
    headers: {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36",
    },
    });
    // Load HTML previously fetched
    const $ = cheerio.load(response.data);

    //grab the metadata
    const jsonData = $("script#__NEXT_DATA__");

    console.log(jsonData.html());

  } catch (err) {
    console.error(err);
  }
}
// Invoke the above function
scrapeData();

I’ve tried running it through untruncate-json but what Cheerio outputs is apparently too damaged to recover functionally.

I’m also running this through a Google Cloud project, if that affects anything.

Making tar files in python

I’m trying to recreate some typescript functions in python.
here is the reference

export interface CollectionEntry<T> {
  data: T

  /**
   *
   */
  path: string
}

/**
 * Represents Collections
 */

// converts a string to utf8 Uint8Array and returns it as a string-like
// object that `tar.append` accepts as path
function fixUnicodePath(path: string): StringLike {
  const codes = new TextEncoder().encode(path)

  return {
    length: codes.length,
    charCodeAt: index => codes[index],
  }
}

export function makeTar(data: Collection<Uint8Array>): Uint8Array {
  const tar = new Tar(1)
  for (const entry of data) {
    const path = fixUnicodePath(entry.path)
    tar.append(path, entry.data)
  }

  return tar.out
}
// input
const directoryStructure: Collection<Uint8Array> = [
        {
          path: '0',
          data: Uint8Array.from([0]),
        },
      ]
makeTar(directoryStructure)

I’m doing this. But the output I’m getting is wrong

def make_tar(data):
    tar_io = io.BytesIO()
    with tarfile.open(fileobj=tar_io, mode="w") as tar:
        for entry in data:
            tar.addfile(tarfile.TarInfo(name=entry["path"]), io.BytesIO(entry["data"]))
    return tar_io.getvalue()

# input
data = [{"path": "0", "data": bytes([0])}]

The first 209 characters are correct. The output should be of 5120 characters but I’m getting 20480

Here is the expected & got results.

P.S. Whoever is downvoting. I may not be a coding pro. This may seem to be a stupid question. You can just ignore it and move on with your life. Don’t ruin my enthusiasm to ask questions.

How to emit event from one namespace to other namespace in serverside without user pass event to client site using SocketIO

I hope this question find you well as I’m new to Node.js and SocketIO?.

I have two namespace in server side adminNamespace and agensiNamespace

Below are event from adminNamespace that listen from client and want to pass new event to agensiNamespace

adminNamespace.on("connection", function (socket) {
    //admin assign to agency event
    socket.on("adminAssignToAgency", function (assignData) {
        agensiNamespace.emit("adminAssignUser", assignData);
    });
});

Below are the code in agensiNamespace that listen to event from adminNamespace

agensiNamespace.on("connection", function (socket) {
    adminNamespace.on("adminAssignUser", function (assignData) {
        console.log("Received event from admin and emitting to agensi:", assignData);
    });
});

Is it possible to do that if yes please give an example on step and explanation if you could.
Thank you in advance

Get all the content of a specific property of an array [duplicate]

I have a javascript array and I need parse it and get all text, bold, italic and underline property content as showing below.

I have trying the next, but it works only for one level of “richtext.children”.

How could I fix it to work with many nested levels of “richtext.children” as the sample below?

messages: [
  {
    id: "ziov7x4u3zhk6br3fjyw8k2w",
    type: "text",
    content: {
      richText: [
        {
          type: "p",
          children: [
            {
              text: "Ola ",
            },
            {
              type: "inline-variable",
              children: [
                {
                  type: "p",
                  children: [
                    {
                      text: "Luiz",
                    },
                  ],
                },
              ],
            },
          ],
        },
      ],
    },
  },
  {
    id: "eflh0riyx9zhy7dh31y25ont",
    type: "text",
    content: {
      richText: [
        {
          type: "p",
          children: [
            {
              bold: "Qual seu email?",
            },
          ],
        },
      ],
    },
  },
];
const parseMessages = (messages) => {
  let result = "";
  for (const message of messages) {
    if (message.type === "text") {
      let formattedText = "";
      for (const richText of message.content.richText) {
        for (const element of richText.children) {
          let text = "";
          if (element.text) {
            text = element.text;
          }
          if (element.bold) {
            text = `*${text}*`;
          }
          if (element.italic) {
            text = `_${text}_`;
          }
          if (element.underline) {
            text = `~${text}~`;
          }
          formattedText += text;
        }
        formattedText += "n";
      }
      if (formattedText) {
        formattedText = formattedText.replace(/n$/, "").split('{"id":')?.[0];
        result += formattedText;
      }
    }
  }
  return result;
};

How to manage states of multiple instances of a functional component from outside the component?

This is something that seems super straightforward to do with class components, but seemingly overcomplicated (with my current level of knowledge) to do without.

I’m trying to work out what the functional equivalent for a similar case to the example below would be, but can’t get my head around how states can be managed for functional components from outside the component.

This example is pretty simple, on ClassComponent mount, the instance of itself is added to the instances array belonging to the Handler class. There is then an interval running in the Handler class which gets a random instance of the component from the array, and changes its state every second – in this case the font color.

<div id="app"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
// Example handler.
class Handler {
  constructor() {
    setInterval(
      this.changeState.bind(this),
      1000,
    )
  }
  
  instances = [];

  addInstance(instance) {
    this.instances.push(instance);
  }
  
  getRandomInstance() {
    const min = 0;
    const max = this.instances.length - 1;
    const num =  Math.floor(min + Math.random() * (max - min + 1));
    return this.instances[num];
  }
  
  getRandomColor() {
    var letters = '0123456789ABCDEF';
    var color = '#';
    for (var i = 0; i < 6; i++) {
      color += letters[Math.floor(Math.random() * 16)];
    }
    return color;
  }

  // Get a random instance from instances and change the state of it.
  changeState() {
    const instance = this.getRandomInstance();
    const color = this.getRandomColor();
    if (typeof instance.setColor === "function") {
        instance.setColor(color);
    }
  }
}

// Example Class component.
class ClassComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { color: '#000000' };
  }
  
  static handler = new Handler();
  
  setColor(color) {
    this.setState({ color: color });
  }
    
  componentDidMount() {
    // Add the instance to the Handler class instances array.
    ClassComponent.handler.addInstance(this);
  }
  
  render() {
    const style = {
      color: this.state.color,
    }
    return (
      <div>
        <p
          style={style}
        >
          Class component = {this.state.color}
        </p>
      </div>
    );
  }
}

function App() {
  return (
    <div>
      <ClassComponent id="class-component-1" />
      <ClassComponent id="class-component-2" />
      <ClassComponent id="class-component-3" />
    </div>
  )
}

ReactDOM.render(<App />, document.querySelector("#app"));

So with this I can easily control the states of each mounted component just using the Handler class. I’m able to use this class anywhere and don’t need to do any weird nesting and passing data/props up or down the tree.

I am confused about how to do a similar thing of accessing/invoking a functional component’s useState setter function, and if I do manage that, how would I identify each one? With classes I can use this and pretty much get everything from there. I have read about using useContext but am failing to see how this could solve a pattern similar to above, especially if instances of the component are scattered all over the codebase. I don’t think any hook-based solution should be used outside the React tree either, for example being called from a local lib function.

I know Redux exists also, but I feel like installing a whole library for something that can be achieved with a single class easily seems like overkill – there must be a pure React equivalent?

I hope this makes sense, and any hints would be hugely appreciated!

how to frequently re-render image in react native without making image flash?

I have a react native app and I need to render a “video” in the app. This “video” works by getting a new image from a url which updates the image every second.

This is my current implementation:

import React from "react";
import { View, Image} from "react-native";

export default class CurrentWebcam extends React.Component { 
    constructor (props) {
        imagesource = {uri:'myurl?'+Date.now()};
        super(props)
    }

    componentDidMount(){
        this.timer = setInterval(() => {
            imagesource = {uri:'myurl?'+Date.now()};
            this.forceUpdate();
          },3000)
    }

    componentWillUnmount(){
        clearInterval(this.updateTimer);
    }

    updatedImage(){
        return (
            <Image source={imagesource}
                   style={{width: 400, height: 400}} />
        )
    }

    render() { 
      return (
        <View> 
            {this.updatedImage()}
        </View> 
      );
    }
  }

The problem I am having is this method causes the image to flash out of existence every time it’s re-rendered instead of simply changing from one image to the next. Also I know this is a really stupid system but I just have to work with it.