Calling local dotnet https backend from local NextJS results in FetchError: self-signed certificate

Viewed 658

I've recently had to switch my local dotnet core 6 backend development to now run on HTTPS due to some Secure cookies being passed between the backend and the front-end. Unfortunately now I'm having some issues when calling it from my NextJS API which is as follows

error - FetchError: request to https://localhost:5001/api/user/login failed, reason: self-signed certificate

My guess would be that it's because I'm not using https for the next.js local server but I don't fully understand why or how to go about that. Any help either with the solution or understanding the problem would be appreciated. Please find below the problematic code block from my NextJS API.

import type { NextApiRequest, NextApiResponse } from 'next';
import { User } from '../../models/User';

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse<User>
) {
  console.log(req.body);
  await fetch('https://localhost:5001/api/user/login', {
    body: req.body,
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    }
  })
    .then((res) => res.json())
    .then((response: User) => {
      res.status(200)
        .json(response);
      console.log('res', response);
    });
}
1 Answers

You need to sign your certificate with Root CA. Then add it to trusted root certificate.

I used Self sign Laragon

but you can generate new one following the step

  1. create RootCA.pem and RootCA.key
  2. create .csr file
  3. issue it with RootCA
  4. add it to trust root certificate

also you need to config req file and domain.ext

sudo openssl req -new -nodes -days 720 -newkey rsa:2048 -keyout /etc/ssl/private/$Domain.key -out /etc/ssl/certs/$Domain.csr -config /certs/openssl.cnf
       
sudo openssl x509 -req -sha256 -days 720 -in /etc/ssl/certs/$Domain.csr -CA /certs/RootCA.pem -CAkey /certs/RootCA.key -CAcreateserial -extfile /certs/domains.ext -out /etc/ssl/certs/$Domain.crt
Related