Next.js Discord

Discord Forum

How to setup HTTPS for Nextjs api routes?

Unanswered
Indian oil sardine posted this in #help-forum
Open in Discord
Indian oil sardineOP
hi, dont know where to ask this since this involve both backend + frontend (nextjs + node/expressjs),

in nextjs in the api routes I am using axios to call the api from another subdomain, this all works well in localhost,

but when I move it to server I need to setup HTTPS to make it work ( the api backend subdomain uses https)

here is how I setup for nextjs frontend api axios with request interceptor:

axiosInstance.interceptors.request.use(
    request => {

        request.httpsAgent = new https.Agent({
            // rejectUnauthorized: false,
            ca: fs.readFileSync('ca.crt'), // put ca.crt in same folder as this file to work?
        })

        // Edit request config
        return request;
        },
);


here is how I setup nodejs backend for HTTPS, but do I really need this to make the frontend api calls successful?

    const privateKey  = fs.readFileSync('./private.key');
    const certificate = fs.readFileSync('./cert.crt');

    const credentials = {key: privateKey, cert: certificate};

    const httpsServer = https.createServer(credentials, app);

    const server = httpsServer.listen(
        PORT,
        hostname,
        (err) => {
            if(err) console.log(err)
            console.log("Server timezone: ", Intl.DateTimeFormat().resolvedOptions().timeZone)
            console.log("Server running on Port: ", PORT)
        }
    )

6 Replies

Sloth bear
why you involve cert handling in your next app? just create https server with express and handle client side ssl stuff with nginx
Indian oil sardineOP
I see, so the axios httpsAgent etc is totally not necessary?
if I remove the axios httpsAgent rejectUnauthorized: false from all the nextjs api routes, the api call will fail though
Indian oil sardineOP
@Sloth bear I am getting request.error, here are the screenshots of the request headers and response headers:
Sloth bear
Seems like a cors error? Whats the error message? Check your console tab.