DEV Community

Jakub T. Jankiewicz
Jakub T. Jankiewicz

Posted on • Updated on

RPC in Next.js

When I was creating web applications I was loving using JSON-RPC. When I started learning and using Next.js I wanted to find JSON-RPC library for next. But I've found something even better.

What is RPC

RPC stands for Remote Procedure Call. Basically it's abstracting the boundary of client server architecture of Web applications. You have a function on the server like echo and you call it from the client (like a browser). The library for RPC just do all the packing and unpacking of the requests and you can think like you just have no server and HTTP protocol between at all. So it simplify a way of thinking about application. Because the best way of simplifying a complex application is to not have to thinking about stuff that are not important at a given moment. This is the whole purpose of abstraction, you name a thing and you can forget what it's inside and have your mind think about order things.

What is JSON-RPC

JSON-RPC is RPC protocol that just sends JSON payload to the server and server unpack the JSON call the method, pack the response in JSON and send it back to the client where client unpack it and get results.

Example:

  • You call function echo("hello, world!")
  • method call is saved as {"method": "echo", "params": ["hello, world!"}
  • JSON is send to the server
  • server call method echo("hello, world!")
  • The result is saved as {"result": "hello, world!"}
  • JSON is send back to the client
  • client return Promise of "hello, world!"

NOTE: some properties of JSON-RPC was left out for simplification, you can read how exactly JSON-RPC works in its specification or on Wikipedia.

So basically you can just think about this like you call server function, call it from browser and get result as promise. You can forget that you even have a server.

JSON-RPC is even even simpler after introducing Promises and async..await into JavaScript, because the JS function on the Front-End can just be async.

With Node.js and JavaScript in browser you can have:

// client
await echo("hello, world!");

// server
async function echo(str) {
   return str;
}
Enter fullscreen mode Exit fullscreen mode

The rest is magically converted to JSON and sent between browser and server but when you write code you can think about browser and server as one entity. Here is simple example but the function can be more complex like reading or writing data into a database.

For me RPC architecture is way superior than REST or GraphQL and it's way underrated.

RCP with Next.js

When I was searching for JSON-RPC implementation for Node and Next. I've found this little gem, library next-rpc.

Using next-rpc is very simple:

First you install the library:

npm install -S next-rpc
Enter fullscreen mode Exit fullscreen mode

Then you need to configure next to use RPC:

// ./next.config.js
const withRpc = require('next-rpc')();
module.exports = withRpc({
  // your next.js config goes here
});
Enter fullscreen mode Exit fullscreen mode

Then you define your remote functions/procedures:

// /pages/rpc/index.js

// this enable RPC mechanism
// if this is not included the route will work normally
export const config = { rpc: true };

// this is remote procedure that you can import and call
export async function getUsers() {
  return db.query(`SELECT users FROM users`);
}
Enter fullscreen mode Exit fullscreen mode

Then you can use this method in any component:

// /components/users.jsx
import { useState, useEffect } from 'react';
import rpc from '../pages/rpc/index.js'

const Users = () => {
   const [users, setUsers] = useState([]);
   useEffect(() => {
      getUsers().then(setUsers);
   }, []);
   return (
      <ul>{
         users.map(user => {
            return <li>{ user.name }</li>;
         })
      }</ul>
   );
};
Enter fullscreen mode Exit fullscreen mode

And that's it, you can also use next-rpc with reactQuery or swr.

Even that this RPC mechanism abstract the usage of the server and HTTP, this library still give you an access to request object, so you for instance can create login and get HTTP headers if you want. But you probably will not do that a lot of times and need it only for special cases.

Conclusion

IMHO any RPC mechanism is way better, than any other server/client approach, when you're developer that work on both Back and Front of the application, the boundary of server/client is blurred completely. And this is how you typically work with Next.js. You can think about the application as one entity (even more than with pure Next.js) and you can forget about not important things like HTTP requests. But still you can think about it when needed, just like with any abstraction, like a function. Most of the time you can use just the name of the function, but sometimes you need to look inside, and this is what next-rpc library gives you and your Next.js application.

If you like this post, you can follow me on twitter at @jcubic.

Discussion (0)