Exploring the capabilities of using Next.js with grpc-node

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.

Answer №1

If you find yourself in that situation, consider utilizing Node.js global

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to eliminate an object from an array of objects depending on a certain condition?

I have an array of objects structured like so: data = [ { "name":"abc", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fa9b9899ba9d979b9396d4999597">[email protected]&l ...

Experiencing problems with npm and bower installations, along with deprecated modules while setting up angular-phonecat project

Trying to execute npm install in terminal while setting up angular-phonecat based on instructions from https://docs.angularjs.org/tutorial Encountering issues with deprecated modules and errors during the bower install phase. Seeking advice on how to upd ...

Tips for ensuring the vertical scroll bar is always visible on a div element

I need help with maintaining a vertical scroll bar on a div regardless of its height. .myclass { overflow-y: scroll; } <div class="myclass"> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the in ...

Verify if a certain value is present within a nested array

I need assistance with checking if a specific value is present within a nested array. Here is an example of the data I am dealing with: [ { name: 'alice', occupation: ['Artist', 'Musician'], }, { ...

Having trouble transmitting parameters through ajax

I have been attempting to use ajax to send variables to a php page and then display them in a div, but unfortunately, it's not functioning as expected. Below is the HTML code: <div id="center"> <form> ...

React: Maximum call stack size exceeded error was caught as an uncaught RangeError

I've been experimenting with React and I've managed to get the functionality I want, but it's running very slow due to an infinite loop lurking somewhere. I suspect the issue lies within the component lifecycle methods, but I'm unsure h ...

Dynamic text displayed on an image with hover effect using JavaScript

Currently, I am in the process of developing a website for a coding course that is part of my university curriculum. The project specifications require the use of JavaScript, so I have incorporated it to display text over images when they are hovered over ...

"Easily toggle the visibility of values in checkboxes and organize them into groups with the power of JavaScript

Hey there! I am currently working on a project that involves grouping checkboxes and hiding/unhiding their content based on user interaction. Essentially, when the page first loads, the "All CARS" checkbox will be checked by default. If I then check the "C ...

Encountering a "No exported member" error while attempting to include & { session: Express.Session } in the MyContext type while following a tutorial on React, Express, and Typescript

Currently exploring a React, Express, and Typescript tutorial, which is still quite new to me. I am trying to grasp the concept of setting up custom types, and this is what I have so far. In my types.ts file: import { Request, Response } from "expres ...

Tips on invoking a method from a JavaScript object within an AJAX request

Considering the following code snippet: var submit = { send:function (form_id) { var url = $(form_id).attr("action"); $.ajax({ type: "POST", url: url, data: $(form_id).serialize(), dataType: 'json', succes ...

React Router's default component for nested routes

In React Router, I am facing a challenge with nested Routes <Route path='about' component={{main: About, header: Header}}> <Route path='team' component={Team} /> </Route> Currently, the Team component is displayed ...

Binding an event to an Angular 2 component directly within its selector code

Looking at my Angular 2 component: import { Component, ElementRef, Renderer } from '@angular/core';; @Component({ selector: 'my-button', templateUrl: 'button.html' }) export class ButtonComponent { private text: string ...

Error message: Unexpected character found at the beginning of JSON data - REST API using node.js and Express

Recently, I have embarked on the journey of learning REST API with node and express. My main goal is to achieve file read and write operations using APIs. However, a frustrating error arises when attempting to hit the API through Postman. Strangely enough, ...

Unclear on the usage of "this" in arrow functions?

After going through various discussions and articles on this topic, I find myself still perplexed about the meaning of this in arrow functions. I've been encountering run-time errors with a code snippet similar to the following: export class Foo imp ...

Console.log is not visible to jQuery's getJSON function

Currently, I am utilizing the getJSON method as shown below: $.getJSON("js/production-data.json").done(function(response) { console.log(response); console.log('hello'); }); While monitoring Firebug, the data retrieval process seems to ...

Searching for a specific data point within the latest entry of a JSON file using Javascript

I am currently in the process of utilizing a sensor to measure temperature, which is then stored in a mongo database. This data can be accessed as a JSON file by visiting ('/data'). My goal is to determine the latest entry and extract the temper ...

Error encountered while attempting to import external JSON data into SurveyJS

This Codepen example showcases SurveyJS using a simple JSON structure: var json = { "questions": [{ "type": "text", "title": "Test question 1", "name": "Test question" }, { "type": "comme ...

Ways to show alternative data from a database in Laravel 8

I am working on a project where I need to display additional data based on the option selected from a dropdown menu populated from a database. Can anyone guide me on how to achieve this using javascript or jquery? https://i.stack.imgur.com/k3WLl.png Belo ...

Can a custom function be executed using setTimeout in Node.js?

I am currently facing an issue with stopping the execution of my code for 2 seconds so that all ongoing animations can finish. I am attempting to implement a delay using setTimeout in Node.js. Here is what I have tried: this.userActivity = function(a,b, ...

Using jQuery's sortable functionality to rearrange rows in a table can cause conflicts with Angular's orderBy feature

In the past, my angular app used a table with orderBy to sort rows based on a specific column. By clicking on a table header, the orderBy arguments would change and the list would be sorted according to the values in that column. Now, I am experimenting w ...