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

The header row in my table multiplies each time an AJAX call is made

HeaderRowMultiplesEachTimeAjax My web grid table in JavaScript consists of a complete HTML table. The top header, which acts like a colgroup caption table, is built through JavaScript insertion as shown below: var headerRow = "<tr><th colspan=&a ...

What are some superior methods for determining the validity of a control in JavaScript?

Is there a way to determine the validity of a control in JavaScript within Asp.Net using a client-side API? Specifically, I am looking for a function that can check if a control is valid based on attached validators. For example, if a textbox has 2 validat ...

Troubleshooting issues with calculator operators in JavaScript for beginners

As a beginner in JavaScript, I've taken on the challenge of building a calculator to enhance my skills. However, I'm having trouble getting the operator buttons (specifically the plus and equal buttons) to function properly. Can someone please as ...

Using jQuery to deactivate buttons upon submission or clicking within forms and hyperlinks

Within my Rails application, there are buttons that send data to the server. Some of these buttons are part of a form while others are standalone. I am seeking a solution to implement my jQuery code, which disables the buttons upon click, for both scenario ...

Concealed Input Enhancements for AutoComplete

Hey there! I'm new to AJAX and could really use some help with my autocomplete function. I'm trying to store the ID of the user's selection in a hidden input field, but I've hit a roadblock. So far, my function isn't working as exp ...

Dealing with challenges in integrating ngx-masonry with Angular 14

I am currently working with Angular 14 framework and the ngx-masonry library (https://www.npmjs.com/package/ngx-masonry/v/14.0.1). However, I am facing some issues where it is not functioning correctly. I would appreciate any assistance or guidance on how ...

Opening a new window with Node-Webkit's start function

My application built on node-webkit has a control window and a separate presentation window. The control window collects data and triggers the opening of the presentation window using the window.open function. Once the presentation window is open, it can ...

Enclose the type definition for a function from a third-party library

I prefer to utilize Typescript for ensuring immutability in my code. Unfortunately, many libraries do not type their exported function parameters as Readonly or DeepReadonly, even if they are not meant to be mutated. This commonly causes issues because a ...

Mobile Chrome allows users to utilize the IFrame player API for enhanced video

Currently, I am working on creating a mobile website where I plan to include some YouTube videos using the IFrame player API (https://developers.google.com/youtube/iframe_api_reference). My main goal is to have the video start playing only after the user ...

Tips for accessing and manipulating an array that is defined within a Pinia store

I have set up a store to utilize the User resource, which includes an array of roles. My goal is to search for a specific role within this array. I've attempted to use Array functions, but they are not compatible with PropType<T[]>. import route ...

Adding custom styles to Material-UI components

` import React, { Component } from 'react'; import Header from './Components/UI/header'; import { Box, Paper } from '@material-ui/core'; import { ThemeProvider, withStyles} from '@material-ui/core/styles'; const ...

Creating a dynamic select input in React that displays a default value based on other user inputs

My dilemma involves working with two radio buttons, named radio1 and radio2, along with a select input. The options available in the select input are conditional based on the selected radio button. I am aiming to automatically set the value of the select t ...

Choose a particular element within an element class using a variable as the selector in jQuery

Is there a way to dynamically add a class to a specific element in an array based on a variable in a for loop, rather than random selection? I need to target elements with the variable provided and possibly apply the class to more than one element if neces ...

Ways to extract variables from a component and utilize them in App.js

Despite my efforts to search online, I could not find the answer or understand what I needed to. My issue: I need the "inputVal" variable from the "InputField.js" component to be accessible in the "App.js" component (specifically in the fetch request where ...

RTK Query - executing a query upon mounting with lazy loading enabled

Should rerendering be triggered by sending a request on mount? Or is the use of useEffect necessary? (Is lazy mode different from regular queries?) export const Catalog: React.FC<CatalogProps> = ({ object, category }) => { const [getCatalogPro ...

Edit CSS attributes within Angular 2+ framework

When using jQuery, we have the ability to do the following: JQuery('.someStyle') .css({"background", "red"}) This allows us to directly change the CSS property in style. While working with Angular 2+, we can use [style.<property>] for ...

In JavaScript, find a value in an array and substitute it with the value from the

One of my tasks involves manipulating a string variable in the following manner: domNodes += '<a href="javascript: void(0);" data-role="node_jump" data-node="'+this.tagName.toLowerCase()+'">'+this.tagName + "</a>" + " & ...

Enhancing visual appearance with customized look control through the use of setAttribute

I have developed a unique custom look-controls feature and I am trying to integrate it into the scene using 'setAttribute(componentName, data)', but I'm unsure about what parameters to include. Any suggestions? Here is my approach: const s ...

Commit to calculating the total sum of each element using AngularJS

Trying to implement a like counter using Facebook's GRAPH API. I have a list of object IDs and for each ID, I make an API call to retrieve the number of likes and calculate a total. The issue arises as the API call returns a promise, causing only one ...

jQuery fails to fetch information

I am currently working with a straightforward script as shown below: $(function() { var url = theme_directory + '/func/api.php'; $.get( url, function(data) { alert("Data Loaded: " + data); }); }); Here is the code for api ...