Next.js with custom(different) nodejs backend

Viewed 237

I have built the frontend part with Next.js so that I can take advantage of SSR and better SEO. And I do have a custom NodeJS+express server for user management and other DB stuff(Fully working with Postman).

Now I want to integrate next.js with my custom-made NodeJS server, how do I do that there are not many resources available to properly execute this.

Please help me out with this not getting anything, how do I integrate them.

If I directly try to access the NodeJS API via URL, say http://localhost:4000/api/v1/register then next.js will throw CORS error, and how will HTTP cookie work? Or I will have to send the JWT token to frontend and save it into local storage and send it with Bearer token.

1 Answers

CORS error might be thrown by node.js. Set the cors in node.js by cors package

const express = require('express');
const cors = require('cors');

const app = express();
// this enables All CORS Requests
app.use(cors())

In case next.js throws an issue, in next.config.js

module.exports = {
    async rewrites() {
        return [
          {
            source: '/api/:path*',
            destination: 'https://api.yourNOdeApi/:path*',
          },
        ]
      },
  };

In next.js, you write lambda functions in pages/api directory. When you make request to outside, you actually send a request to those API routes and inside api routes, you handle the business logic

Related