Search code examples
node.jsreactjsexpressnext.jsserver-side-rendering

Internal API calls and communication between NextJS app and express server


I have a NextJS app with a custom express server. My pages/index.js is making an internal call to my express route /api/users. This is done using isomorphic-unfetch inside getinitialprops() like this:

const res = await fetch('http://localhost:3000/api/users');

My custom express server on top of NextJS has API routes that send back JSON data. Like so:

//some code before
const app = next({ dev })
const handle = app.getRequestHandler()
let apiRoutes = require('./routes/apiRoutes.js');

app.prepare().then(() => {
  const server = express()

  server.use('/api', apiRoutes);

  server.get('*', (req, res) => {
    return handle(req, res)
  })

//more code

So my question is, is this the way to communicate between the my client side code and server side code? If so:

  • How do I protect these endpoints so that the user doesn't just type in myNextJSwebsite.com/api/users and get a JSON response?

Solution

  • This is a common pattern to separate between api & renderer.

    In order to secure your api end-point you will need to implement some kind of authorization, there is common lib for auturization in express, called passport, you can check the types, it supports most of the common methods.

    I personally prefer the JWT way, because it allows to work with many instances of my server due to the fact that there are no user session on the server.