Leveraging the power of Next.js version 13 in tandem with Elastic

I can't seem to figure out why I am getting an error when trying to read from an existing index using this API route and client-side page setup:

import { Client } from "@elastic/elasticsearch";
import { NextResponse } from "next/server";

export async function GET(request) {
  try {
    const client = new Client({ node: "http://localhost:9200" });

    const { body } = await client.search({
      index: "game-of-thrones",
      size: 100,
      body: {
        query: {
          match_all: {}
        }
      }
    });

    const hits = body.hits?.hits || [];
    const documents = hits.map((hit) => hit._source);

    return NextResponse.json(documents, { status: 200 });
  } catch (error) {
    console.error("Elasticsearch Error:", error);
    return NextResponse.error();
  }
}
'use client';
import { useEffect, useState } from 'react';

export default function Home() {
  const [documents, setDocuments] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('/api/all');
        const data = await response.json();
        setDocuments(data);
        setLoading(false);
      } catch (error) {
        console.error('Error fetching documents:', error);
      }
    };

    fetchData();
  }, []);

  return (
    <main>
      {loading ? (
        <p>Loading...</p>
      ) : (
        <div>
          {documents.map((document) => (
            <div key={document._id}>
              <h2>{document.character}</h2>
              <p>{document.quote}</p>
            </div>
          ))}
        </div>
      )}
    </main>
  );
}

Here is how my index looks like:

{"took":3,"timed_out": ... (omitted for brevity) }

Any help on how to correctly return the desired documents would be appreciated. Thanks!

Answer №1

I successfully resolved the issue using this method

Server

import { Client } from "@elastic/elasticsearch";
import { NextResponse } from "next/server";

export async function GET(request) {
  try {
    const client = new Client({ node: "http://localhost:9200" });

    const { body } = await client.search({
      index: "game-of-thrones",
      query: {
        match_all: {}
      }
    }, { meta: true });

    console.log('body', body);

    return NextResponse.json(body, { status: 200 });
  } catch (error) {
    console.error("Elasticsearch Error:", error);
    return NextResponse.error();
  }
}

Client

'use client';
import { useEffect, useState } from 'react';

export default function Home() {
  const [documents, setDocuments] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('/api/all');
        const data = await response.json();
        setDocuments(data.hits.hits.map((hit) => hit._source));
        setLoading(false);
      } catch (error) {
        console.error('Error fetching documents:', error);
      }
    };

    fetchData();
  }, []);

  return (
    <main>
      {loading ? (
        <p>Loading...</p>
      ) : (
        <div>
          {documents.map((document, index) => (
            <div key={index}>
              <h2>{document.character}</h2>
              <p>{document.quote}</p>
            </div>
          ))}
        </div>
      )}
    </main>
  );
}

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

A guide to replacing or customizing standard components in ReactJS

I need to modify the color property of a common component so I can use it elsewhere. const ViewAllIcon = (props) => ( <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 26 ...

Adjusting the color of a specific part of a text within a string using

I am trying to update the color of specific keywords within a post. For example: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam tempor lacinia urna eget gravida. Quisque magna nulla, fermentum fermentum od #keyword1 #keyword2 #keyword3 ...

Steps to designing an Arrow with styled-components

I am currently working on customizing my orange arrow to resemble the pink arrow, but I want to achieve this without relying on an external CSS library like bulma. The reason the pink arrow looks different is because it utilizes the bulma library in its st ...

Ensure your mobile device is age 13 or over before proceeding

I am developing a project with Next js. Here, I want to render a component if it is a mobile device. However, if I use the isMobileDevice value in jsx, I get the errors below. import useTranslation from "next-translate/useTranslation"; import isM ...

Is it possible to customize the default styling options in Tailwind?

I am currently working on a blog using NextJS, and I have encountered an issue with Tailwind's list style type. It seems that the default styling for list style type is set to list-none, resulting in my <ul> <li> elements not being styled ...

What could be causing my Next.js layout to re-render?

I currently have a basic root layout set up in Nextjs (app router) that displays a navigation bar and the child components underneath it. ROOT LAYOUT import "./globals.css"; import type { Metadata } from "next"; import { Inter } from & ...

Creating a menu that is even more optimized for mobile devices

I recently came across a mobile menu style that I really like: https://www.w3schools.com/html/default.asp What I appreciate about this style is that even on smaller screens, it still displays some main navigation items. This allows for popular links to be ...

What could be preventing my state from changing to false when I click the close button on the menu?

Despite initializing my state to false, the problem arises when I open and close my menu. The state never actually becomes false, causing the closing animation of the NavBar to not run as expected. The component: import CloseButton from "./CloseButto ...

Tips on incorporating several class names into Next.js elements

My current challenge involves an unordered list element with the following structure: <ul className={styles["projects-pd-subdetails-list"]}> {detail.subdetails.map((sub) => ( <li className={styles[ ...

Solve the problem with SCSS at the component level in NextJS

I've decided to transition my regular React app to Next.js. In the past, I would simply import SCSS files using: import from '.componentName.scss' However, now I need to import them using: import style from 'componentName.module.scss ...

Resolving the Material-UI NextJS Button Styling Dilemma

I've encountered an issue with the styling of a few buttons in JS. When I apply a styling class using className, the formatting works fine on the initial render but loses its styling on subsequent refreshes. This problem is specific to two individual ...

The process for incorporating two distinct Google fonts into a Next.js project using Material UI

Currently in the process of upgrading my MUI5 application from Next 12 to Next 13 and experimenting with integrating next/font. In my previous Next 12 version, I utilized two Google fonts - 'Rubik' and 'Ephesis' which were included in t ...

Adjust Sidebar Height to Match Document Height (using React Pro Sidebar)

Having an issue with the height of a sidebar component in Next.js using React Pro Sidebar. It seems to be a JavaScript, HTML, and CSS related problem. I've tried several suggested solutions from Stack Overflow, but none of them seem to work. Surprisin ...

Is there a way to remove the scrollbar from the menu created with react-burger-menu?

How can I remove the scroll bar from the menu created with react-burger-menu? Despite trying various CSS properties adjustments, I have not been able to achieve the desired effect. Here is an image of the open menu and the corresponding CSS: (https://i.st ...

How can we display an absolutely positioned div when hovering over a card with the help of Tailwind CSS?

I am currently working on a Next.js application with Tailwind CSS. I would like to implement a feature where additional information is displayed when hovering over a product card, similar to the functionality seen on wildberries.ru. I have tried using &apo ...

The styles for the React calendar are not being properly applied to the calendar component due to CSS overriding

Having trouble overriding the default Calendar.css file in NextJS while creating a calendar component. Even after adding my own custom styles, they aren't being applied. Deleting the css file contents doesn't change the format either. Only when c ...

The div container is not expanding to full width on mobile screens when using Next.js and Tailwind CSS

My goal is to make my div stretch or go full width similar to the table on my page. I have experimented with max-w-full, w-screen, and w-full, but the div is not extending all the way... https://i.stack.imgur.com/8BJnI.png This is the code for my page. ...

A guide on changing the style of a Layout component in React

Currently, I am utilizing Next.js alongside Material-UI as the framework of choice. Within my project, there is a Layout component that encapsulates the content with Material-UI's <Container>. I desire to customize the style of the Layout compon ...

Ways to achieve a gradient effect on top of an image

Hey, I'm trying to implement a gradient on images in my project. Here's what I have so far: import Image from 'next/image' import Box from 'mui/material/Box' import PlayIcon from './PlayIcon.tsx' <Box ...

Modify the font style of numbers based on the keyboard language selected by the user

Is it possible to change the font family of numbers in input fields based on the user's keyboard language? For example, if the user is typing in Persian, the numbers should be displayed in a Persian font, and when they switch to an English keyboard, t ...