RPC in Next.js
Tags: nextjs, javascript, react
Published: 2021-09-28 14:47:45

---
title: RPC in Next.js
published: true
description: 
tags: nextjs, Javascript, reactjs
---

When I was creating web applications I was loving using [JSON-RPC](https://en.wikipedia.org/wiki/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](https://www.jsonrpc.org/specification) or on [Wikipedia](https://en.wikipedia.org/wiki/JSON-RPC).

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:

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

// server
async function echo(str) {
   return str;
}
```

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](https://en.wikipedia.org/wiki/Representational_state_transfer) or [GraphQL](https://en.wikipedia.org/wiki/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](https://github.com/Janpot/next-rpc).

Using `next-rpc` is very simple:

First you install the library:

```bash
npm install -S next-rpc
```

Then you need to configure next to use RPC:

```javascript
// ./next.config.js
const withRpc = require('next-rpc')();
module.exports = withRpc({
  // your next.js config goes here
});
```

Then you define your remote functions/procedures:

```js
// /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 * FROM users`);
}
```

Then you can use this method in any component:

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

const Users = () => {
   const [users, setUsers] = useState([]);
   useEffect(() => {
      rpc.getUsers().then(setUsers);
   }, []);
   return (
      <ul>{
         users.map(user => {
            return <li key={ user.id }>{ user.name }</li>;
         })
      }</ul>
   );
};
```

And that's it, you can also use next-rpc with [reactQuery](https://react-query.tanstack.com/) or [swr](https://swr.vercel.app/).

Even though this RPC mechanism abstract the usage of the server and HTTP, this library still give you 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](https://twitter.com/jcubic) and check my [home page](https://jakub.jankiewicz.org/).

Here you can find some [NextJS jobs](https://www.whatjobs.com/jobs/nextjs).