I am currently utilizing gRPC in my project, but I am encountering an issue when trying to initialize the service within a Next.js application.
Objective: I aim to create the client service once in the application and utilize it in getServerSideProps
(without using client-side routing).
For instance, if we have a service generated with grpc-tools (only available on SSR), I simply wish to initialize it in a specific location. Initially, I thought this could be achieved by creating a custom server.js
:
const { credentials } = require('@grpc/grpc-js');
const express = require('express');
const next = require('next');
const { MyserviceClient } = require('./gen/myservice_grpc_pb');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
// Initialize & Export
exports.myService = new MyserviceClient(
'http://localhost:3000',
credentials.createInsecure(),
);
(async () => {
await app.prepare();
const server = express();
server.get('*', (req, res) => handle(req, res));
server.listen(process.env.PORT, () => {
console.log(`Listening at http://localhost:${process.env.PORT}`);
});
})();
Subsequently, the initialized service can be used on the homepage like so:
import React from 'react';
const { GetSmthRequest } = require('../gen/myservice_pb');
const { myService } = require('../server.js');
const IndexPage = () => (
<div>
<span>My HomePage</span>
</div>
)
const getServerSideProps = async () => {
const request = new GetSmthRequest();
request.setSomeStuff('random');
myService.getStmh(GetSmthRequest, (err, res) => {
//...
})
return {
props: {
}
}
}
export default IndexPage;
However, for some reason, initializing the client service in the server.js
seems to be problematic.
Another approach I tried involved using next.config.js
:
const { credentials } = require('@grpc/grpc-js');
const { MyserviceClient } = require('./gen/myservice_grpc_pb');
module.exports = {
serverRuntimeConfig: {
myService: new MyserviceClient(
'http://localhost:3000',
credentials.createInsecure(),
),
},
};
This solution works well, allowing me to use the service via serverRuntimeConfig
, thereby initializing it only once throughout the entire application. However, when making a request using getServerSideProps
, I encounter an error:
Request message serialization failure: Expected argument of type ...
Error Explanation: ()
The error message indicates that the message serialization - the transformation of the message object passed to gRPC into binary data - has failed. This typically occurs because the message object does not match the expected message type or is otherwise invalid.
If anyone knows why I am encountering this error, I would appreciate insights or examples of utilizing Next.js with grpc-node.