Utilizing NextJS to efficiently route requests directly to the backend and send the responses back to the client within the

In the technology stack for my project, I am using a Next.js server for the front end and a separate back-end server to handle user data storage.

When a client needs to send a request to the back end, they first make an API request to the Next.js server, which then communicates with the back-end server to retrieve the necessary data.

The challenge I am facing is effectively forwarding these requests from the client to the server and handling the response without losing any data or creating messy code.

Currently, this is the approach I have implemented:

export default function handler(req: NextApiRequest, res: NextApiResponse){
    fetch(url, {
        method: "post",
        body: req.body
     }).then(response => res.status(200).json(response.body))
}

However, one major issue with this solution is that it does not include the necessary headers. While I could manually add specific header fields, this approach is not scalable as there are numerous other fields to consider. I am looking for a more comprehensive way to ensure that all required headers are included.

Important Note: The reason I need to intercept the request is to insert a JWT token for authentication purposes.

Answer №1

My backend is built in node js and my frontend is using Next.js. I have been implementing this approach and I must say, it has been quite impressive.


    export const resendSingupOtpAction = action({}, async () => {
      const res = await fetch(
        `${process.env.BACKEND_BASE}/users/resend-signup-otp`,
        {
          method: 'POST',
          headers: { ...getAuthorizationHeader() },
        }
      );
    
      if (!res.ok) {
        return getApiError(res);
      }
    
      const { messsage } = await res.json();
      return { success: messsage as string };
    });
   
    export const setSecureJwt = (tkn: string) => {
      cookies().set(COOKIES.JWT, tkn, {
        secure: true,
        httpOnly: true,
        sameSite: true,
      });
    };
    
    export const deleteSecureJwt = () => {
      cookies().delete(COOKIES.JWT);
    };
    
    export const getApiError = async (response: Response) => {
      const data = await response.json();
    
      return {
        error: (data?.message?.length
          ? data.message[0]
          : 'server_error') as string,
      };
    };
    
    export const getAuthorizationHeader = () => {
      const token = cookies().get(COOKIES.JWT)?.value;
      if (!token) return false;
      return { Authorization: 'Bearer ' + token };
    };
    
    
    export const getJsonTypeHeader = () => {
      return { 'Content-Type': 'application/json' };
    };

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

Issues arising with shadows in THREE.js

I've been struggling to get shadows to work in this fiddle despite trying various configurations. I've looked at other similar questions, tried all the suggested solutions, but still nothing... My current settings include: this._box.castShadows ...

What are some ways to adjust the page being served in node.js?

I have set up my server.js file with necessary dependencies and routing for handling POST requests. However, I am looking to dynamically update the webpage served by this server when a POST request is received on /message endpoint. These requests are trigg ...

Tips for recognizing hyperlinks within a block of text and converting them to clickable links in Angular 2

My task is to create clickable links within a paragraph of strings. I tried using a custom pipe, but seem to be missing something essential. Here's my attempt: import { Pipe, PipeTransform } from '@angular/core'; import { DecimalPipe ...

Ways to access information from doc.data()

<template> <div> {{ id }} {{ title }} </div> </template> <script> import { useRoute } from 'vue-router' import 'firebase/firebase-firestore' import { db } from '@/fdb' export default ...

Having trouble with accessing input field in a modal that was generated by TinyMCE React within a Next.JS environment

In my current project, I am utilizing Next.JS and looking to incorporate the TinyMCE editor onto my webpage. Here is the code snippet I have implemented: <TinyMceEditor selector='textarea' initialValue={ props.value } apiKey=<AP ...

retain the input data from the form by using the keyup event

Currently, I have a scenario where an input field is used to capture user input. Instead of displaying the entered value directly, I am looking to store it in a variable and subsequently use it to retrieve data from a database. Below is the code snippet I ...

Changing Table Cell Color with Bootstrap Based on Value

I have implemented Bootstrap tables into my project using the tables provided on this website Bootstrap Tables and I am populating data from my MongoDB to these tables. One of the fields in my table is labeled "ACTIVE" and I am looking for a way to dynami ...

Having trouble retrieving information from .pipe(map()) method

Encountering some issues with Observable handling. I have a function that returns an Observable. public getData(userId) { const data = this.execute({userId: userId}); return {event: "data.get", data: data} } private execute(input: SomeDt ...

Leveraging redux within your NEXT.JS project

While working on my Next.js application, I have integrated Redux and Redux Saga. I am trying to incorporate server-side rendering for making HTTP requests: export const getStaticProps = wrapper.getStaticProps(async ({ store }) => { store.dispatch(g ...

What are the differences between performing a search in MongoDB (database component) and Node.js (server-side)?

1) My input consists of a string with approximately 30 comma-separated elements, such as str1, str2, str3, etc. This is represented by "INPUT_STRING". 2) Within my MongoDB collection, I have a set of "allowed_strings" which includes entries like str1, str ...

Flask caches JSON files automatically

I am currently working on a visualization app using js and python. The functionality of my app is as follows: There is a textbox in the browser where I input an URL The URL is then sent to Python via Flask In Python, the URL is processed to create ...

Using *ngIf to construct SVG icons in Angular 2 doesn't contribute to the DOM in any way

I am currently utilizing icoMoon to import a series of SVG icons. The structure of the html I'm trying to create using ngIf is as follows: <div class="contactIcon"> <svg class="icon icon-envelop"> <use xlink:href="symbol-d ...

Redux ConnectedProps will always have a type of never

I am facing an issue while attempting to connect a component to my Redux store following the steps outlined in the official documentation guide. The props that are connected seem to be coming through as type never. Here is a snippet of my code: Type defi ...

Verifying with VueJS and Jest: How to test if a component's method calls an imported function

I've created a VueJS 2 component that has the following structure: <template> <div> <button @click="onFavorite"> Add to favorites </button> </div> </template> <script> import { tra ...

Tips for extracting popular song titles from music platforms such as Hungama or Saavn

I am looking to retrieve the names of the top trending songs/albums from platforms such as Hungama or Saavn. I experimented with web scraping packages available on npm to extract data from websites, including cheerio, jsdom, and request. Eventually, I came ...

Tips for managing errors when utilizing pipe and mergemap in Angular

In the code snippet provided, two APIs are being called. If there is an error in the first API call, I want to prevent the second API call from being made. Can you suggest a way to handle errors in this scenario? this.userService.signUp(this.signUpForm.v ...

Importing whole sass files or modules in a NextJS page or component

I'm attempting to import CSS in the same way I typically do in React. import "@styles/my_lovely_component.sass" However, I encountered an error stating that I cannot import global styles into components. Changing the file name from my_lovel ...

Drag and drop feature malfunctioning - items cling to one another and rearrangement is imprecise

For my current project, I am utilizing react-beautiful-dnd, Chakra UI, and Next.js. If you're interested in seeing the issue in action, check out this video: https://youtu.be/8maSmqahjfw. Despite attempting various methods like ondragupdate, ondragsta ...

Building a sub route in React Router v4 allows developers to efficiently organize and manage

Before starting, I familiarized myself with the concept of react router by visiting https://reacttraining.com/react-router/web/guides/quick-start. I have developed a simple 3-page site in react and now want to create a list that will allow me to display so ...

Ways to attach an item using its lower point instead of its upper coordinate

I am currently working on a poker table project using React. As of now, I have player components that need to be strategically positioned around the table. https://i.sstatic.net/gX9Ij.png One challenge I'm facing is that when the screen attribute ch ...