Encountering a Next.js application error while utilizing the button tag in conjunction with generating metadata

I keep encountering an issue with generateMetaData when trying to utilize the button tag. Can you help me resolve this problem?

Currently, I am working with nextjs and I am unable to properly use the <button> tag.

Whenever I implement generateMetaData provided by nextjs, I receive the error message "Application error: a client-side exception has occurred (see the browser console for more information)."

This is how I define my generateMetaData code:

const getArticle = cache((id) => {
  const articleService = new ArticleService();
  return articleService.getOne(id).then((res) => {
    return res.resultFinal;
  });
});

export async function generateMetadata({ params }) {
  const id = params.id;
  const articleService = new ArticleService();

  const article = await articleService.getOne(id).then((res) => {
    return res.resultFinal;
  });

  if (!article) {
    return {
      title: "Article not found",
      description: "Article not found",
      openGraph: {
        title: "Article not found",
        description: "Article not found",
      },
    };
  }

  return {
    title: article.title,
    description: article.description,
    openGraph: {
      title: article.title,
      description: article.description,
      images: [process.env.NEXT_PUBLIC_IMAGE_BASE_URL + "/" + article.medias[0].url],
    },
  };
}

Here is a snippet of my component:

export default async function Page({ params, searchParams }) {
  const article = await getArticle(params.id);

  const sharedFacebook = async () => {
    alert("clicked");
  };

   return (
      <>
      <button onClick={sharedFacebook}></button>
      </>
    )
}

Adding "use client" in the sharedFacebook function seems to work, but clicking the button still triggers the "Application error..." message:

The same issue occurs when I add "use client" at the beginning of my component.

Answer №1

Page acts as a Server Component while <button> functions as a Client Component [1]. The function sharedFacebook is non-serializable, meaning only serializable props can be passed from Server Components to Client Components.

To resolve this issue, you must transfer the event handler sharedFacebook to a Client Component.

// app/page.tsx

import {Button} from "./button";

export default async function Page({ params, searchParams }) {
  const article = await getArticle(params.id);

   return (
      <>
        <Button />
      </>
    )
}
// app/button.tsx
"use client";

export function Button() {
  const onClick = () => {
    console.log("clicked!")
  }

  retrun <button onClick={handler}>Click Me</button>
}

  • [1] Essentially, every html built-in element serves as a client component since the browser alone understands how to interact with them.

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

Using javascript to transform the entire list item into a clickable link

Currently, I am using PHP in WordPress CMS to populate slides on a slider. Each slide contains a link at the bottom, and my goal is to target each slide (li) so that when clicked anywhere inside it, the user is directed to the URL specified within that par ...

jQuery's AJAX functionality may not always register a successful response

Below is the code snippet I am currently working with: $(".likeBack").on("click", function(){ var user = $(this).attr("user"); var theLikeBack = $(this).closest(".name-area").find(".theLikeBack"); $.a ...

Top technique for verifying the presence of duplicates within an array of objects

How can I efficiently check for duplicates in typescript within a large array of objects and return true or false based on the results? let testArray: { id: number, name: string }[] = [ { "id": 0, "name": "name1" }, ...

What is the reason for the malfunctioning of this button upon clicking?

Attempting to customize my personal website by making the sidebar width change when the sidebar button is clicked. I'm puzzled as to why it's not working as intended. I prefer to figure it out independently but any helpful tips would be appreciat ...

Child component in Angular2 makes an observer call to its parent object

Let me try to explain this in the best way possible. I have a service that includes an observable class responsible for updating itself. This observable class needs to be pushed out to the app using the observer within the service. How can I trigger that ...

Expanding URL path parameters in Angular's ui-routerWould you like to

Can UI-router handle this type of routing? Parent state - /saved/:id Child state - /saved/:id/eat Here is the code snippet I am using. However, when I attempt to access it, the page redirects: .state('fruits.banana.saved', { url: &apo ...

Using jQuery checkboxes with ajax for data submission and storage in PHP without the need for insertion

Seeking guidance on how to properly serialize elements value instead of pushing it, as I am encountering an issue where each value is being inserted into the database 9 times. Any assistance in figuring out this problem would be highly appreciated. The HT ...

What is the technique used by express.js to handle ReferenceError?

// Here is a sample code snippet app.get("/test", (req, res) => { return res.status(200).send(SOME_UNDEFINED_VAR); }); If a ReferenceError occurs, express.js will automatically send a 500 error response. express.js logs the ReferenceError to std ...

Create a new division directly underneath the bootstrap column

Imagine having a bootstrap table like this: https://i.sstatic.net/kXHiP.jpg Now, if you want to click on a column and open a div with more details below it, is it achievable with CSS or JavaScript? https://i.sstatic.net/HIfkK.jpg I tried using the Metr ...

Three.js is failing to render within a specified div

My current project involves utilizing three.js to create a cube rendering. Despite the cube appearing on the screen, I am facing issues with getting it to display within the specified div element and in the desired style. HTML: <div id="render"> & ...

What is the best way to vertically flip a background image that is repeating along the y axis in CSS?

I am in the process of developing a mobile web app and I need assistance with flipping the background image when it repeats along the y-axis. Can someone guide me on how to achieve this using CSS or JavaScript? https://i.stack.imgur.com/b107V.jpg var el ...

Node.js in action with XmlHttpRequest

I'm having trouble making an XMLHttpRequest call from my client-side JavaScript to my Node server. It seems like nothing is happening and I'm a bit new to this concept. Here's the JavaScript function I've written: function sendTokenToS ...

ACL - Utilize ACL in conjunction with the passport authentication system

I am experimenting with node_acl in combination with passport-local. Unfortunately, I am facing an issue when trying to secure the route for the admin-user '/admin', as it keeps redirecting me to the /login page. Below is a simplified version of ...

Having Trouble with CORS when Sending a POST Request to Next.js 13.4.4 API Endpoint

I am currently using Next.js version 13.4.4 and have set up an endpoint at http://localhost:5000/logout. Within my src/app/logout/route.tsx file, the following code is present: import { NextRequest, NextResponse } from "next/server"; export asyn ...

Tips for receiving feedback when uploading multiple images

I've been facing challenges with receiving a response when uploading multiple images using the API. Despite getting a valid response when uploading a single image, I'm not getting the expected response for multiple uploads. Below is my code: fil ...

Is there a method in NextJS to trigger an action exclusively on the server side during a newly loaded page?

At first, our team developed an _app.tsx file with getInitialProps, and included this line: if (!req) return {}; The goal was to ensure that getInitialProps only runs server-side during the initial page load. This decision was based on common advice found ...

Coding with Angular 4 in JavaScript

Currently, I am utilizing Angular 4 within Visual Studio Code and am looking to incorporate a JavaScript function into my code. Within the home.component.html file: <html> <body> <button onclick="myFunction()">Click me</button> ...

VueJS integrated with FullCalendar: Dynamically load FullCalendar only after linking required scripts in index.html

When trying to incorporate fullCalendar into my Vue component, I encountered the error message "fullCalendar is not a function." It appears that the scripts I have included in my index.html file are loading after the Vue component has already been loaded. ...

Issues with invoking C# event through ajax communication

Whenever I click the Button, an Ajax method is called that triggers a webmethod on the server side. However, currently, the [WebMethod] is not being executed as expected. Below are the snippets of both the Ajax and server-side code: Ajax code $(document ...

Dynamic Loading of Multiple Scripts on a Webpage with Dependencies in JavaScript

I am currently working on developing a page constructor entirely using JavaScript. The issue arises when I dynamically add two scripts to the page that are dependent on each other. For instance, in this scenario, I am loading jQuery from a CDN, and in the ...