SSL Connection Issues Between Next.js Frontend and Express Backend

I’m facing difficulties in configuring my local setup with SSL. My frontend is developed using Next.js and runs on port 3002 with the experimental HTTPS feature active. Meanwhile, my backend is set up with Express on port 8080.

Here’s how I set up SSL for the backend:

const httpsConfig = {
  key: fs.readFileSync('./ssl/private.key'),
  cert: fs.readFileSync('./ssl/certificate.crt'),
  ca: fs.readFileSync('./ssl/authority.crt')
};

https.createServer(httpsConfig, server).listen(serverPort, () => {
  console.log(`Server running securely on port ${serverPort}`);
});

In my frontend, I attempt to make an API call like this:

const apiResponse = await fetch('https://localhost:8080/api/signup', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(userData),
});

if (apiResponse.ok) {
  console.log('Signup successful');
} else {
  console.error('Signup failed');
}

While I can access my backend endpoints via Postman without any issues, the frontend’s requests are resulting in CORS errors indicating that the requests are failing.

For handling CORS on the backend, I’ve configured it as follows:

const corsConfig = {
  origin: 'https://localhost:3002',
  optionsSuccessStatus: 200,
};
server.use(cors(corsConfig));

Both components function properly on their own, yet they’re unable to interact with each other. Can anyone help me figure out what’s wrong?

I encountered a similar issue when developing with local SSL certificates. The problem likely stems from your Next.js frontend not trusting the SSL certificate used by your Express backend. Even though Postman works fine, browsers are more strict about certificate validation. Try adding process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0' temporarily in your Next.js development environment to bypass certificate validation, or configure your fetch request with a custom agent that ignores SSL errors. Another approach is ensuring both services use certificates signed by the same local certificate authority. Also verify that your CORS middleware is placed before any route handlers in your Express setup, as middleware order can affect request processing.

hmm this is intresting - are you seeing any specific error messages in your browser’s dev tools? also curious what ssl certificates you’re using for local dev - self-signed ones can cause wierd issues with cors even when postman works fine. have you tried testing the connection without ssl first to isolate the problem?

sounds like a cert issue to me. try hitting your backend directly in the browser at https://localhost:8080 - you might see a security warning that you’ll need to accept. browsers are strict with self-signed certs unlike postman which just goes ahead and ignores.