What is causing this NextJS function to function correctly on a local server but not when deployed on AWS Lambda?

I've spent a lot of time testing and researching this issue, but I haven't been able to solve it. I have a function that runs perfectly fine on my local machine (no errors), but fails when deployed as an AWS Lambda.

To demonstrate the problem, I created a simple example:

LOCAL URL: http://localhost:3000/flagTest/visible (works fine ✅)

LAMBDA DEPLOYED URL: (Toggle button doesn't work ❌)

FILE: /pages/flagTest/[tid].js (on a basic NextJS setup)

import React from 'react'


class FlagTest extends React.Component {
  static async getInitialProps({ query }) {

    return { visible: query.tid }

  }

  constructor(){
    super();

    this.state = {
      showFlag:false,
    }

  }

  componentWillMount(){
    this.setState({ showFlag: this.props.visible === 'visible'  });
  }

  handleToggle =()=> {

    this.setState({
      showFlag:!this.state.showFlag
    });
  }

  render() {

    return (
      <div>
        <h1>Flag: {this.state.showFlag ? '🏁' : ''} </h1>

        <button className='list_toggle' onClick={this.handleToggle}>
          {this.state.showFlag ? 'Hide Flag': 'Show Flag'}
        </button>

        <hr/>

        Props:
        <pre>
          {JSON.stringify(this.props, null, 2)}
        </pre>
        State:
        <pre>
          {JSON.stringify(this.state, null, 2)}
        </pre>

      </div>
    );

  }
}

export default FlagTest

Note: I'm using getInitialProps because I plan to use it in a more complex scenario involving API fetching by id. I didn't include it here because it's not directly related to this issue.

This is my Serverless YML configuration

service: A123-serverless

provider:
  name: aws
  runtime: nodejs8.10
  stage: ${self:custom.secrets.NODE_ENV}
  region: us-west-2
  environment:
    NODE_ENV: ${self:custom.secrets.NODE_ENV}

functions:
  server:
    handler: index.server
    events:
      - http: ANY /
      - http: ANY /{proxy+}

plugins:
  - serverless-apigw-binary
  - serverless-domain-manager

custom:
  secrets: ${file(secrets.json)}
  apigwBinary:
    types:
      - '*/*'
  customDomain:
    domainName: ${self:custom.secrets.DOMAIN}
    basePath: ''
    stage: ${self:custom.secrets.NODE_ENV}
    createRoute53Record: true
    endpointType: 'regional'

Thank you!

Answer №1

I managed to solve my issue and wanted to share the solution in case anyone else encounters the same problem:

The issue I faced was with extracting the 'id' using "query". While it worked fine on a local environment, it needed to be passed as a parameter on the Server Side when using Express. Here's how you can do it:

server.get("/q/:id", (req, res) => {
  return app.render(req, res, "/q/_tid", { id: req.params.id });
});

In your React component, you can then access and use this 'id' in getInitialProps as req.params.id

static async getInitialProps({ req }) {

      myId = req.params.id

}

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

VSCode is experiencing issues with recognizing .env* files for markup purposes and is also failing to recognize .env.local.* files

Current Environment: Utilizing NextJs, React, and VsCode Noticing a problem with syntax highlighting in my VSCODE editor. I have installed the following extensions: ENV DotEnv As per suggestions, I updated my json configuration file as follows: " ...

Encountering a 404 error page when attempting to access the NextJs App build, even though it is functioning perfectly in development mode

As a newcomer to React/Next JS, I encountered an issue after purchasing a theme and customizing the configuration and branding. Running the app with "yarn dev" and "yarn start" works fine, and "yarn build" produces an optimized production build. In my atte ...

Leveraging require in AWS lambda operations

As part of my exploration into AWS Lambda functions, I've been trying to determine if the require statement can be used within them. This would allow me to incorporate other non-lambda functions into my code. Although zipping the node modules folder i ...

Update the state of the parent component based on changes made in the child component (both are functional

Here is the layout for the current issue: . ├── components │ ├── ModalPolicy.js │ ├── Footer │ ├── index.js ├── pages │ ├── index.js I attempted to display the Modal on Footer/index.js but it did no ...

Ways to generate multiple instances using create-next-app

I'm currently using this tool to help me develop a Next app: Encountering the following issue: create-next-app --example with-next-i18next with-next-sass with-next-seo next-learn An error occurred. The example named "with-next-i18next" could not be ...

Utilizing Foundation and jQuery in a Next.js web development project

I've been attempting to incorporate Zurb Foundation's scripts into my next js application, but I keep encountering an error message when trying to include the Foundation core. The error I'm seeing is: /Users/alasdair_macrae/Sites/merlin/spa_ ...

Encountering a 404 error while trying to access dynamic routes in Next.js

I created a dynamic route named [results].js import { useRouter } from 'next/router' const Post = () => { const router = useRouter(); const { results } = router.query; return <p>Post: {results}</p> } export default P ...

Transferring a file from Django's FileField to the public directory in Nex.js

Is there a way to upload files in Django to a directory located outside of the project folder? I am attempting to upload a file or image from the front-end (Next.js) using a FileField in Django and store it in the public directory of the Next.js project, ...

I keep getting a 404 error when trying to use Internationalization (i18n) Routing

I want to implement multiple languages on my website using Next.js. I have made some configurations in next.config.js /** @type {import('next').NextConfig} */ const nextConfig = {} module.exports = nextConfig module.exports = { i18n: { l ...

Docker Container Crashing without Any Error Logs in NextJS Application

Currently, I am facing an issue with running a NextJS app in a docker container. To connect to my database, I am utilizing Prisma and implementing NextAuth for OAuth. When running the application on my local machine, the login process works smoothly as ex ...

When using Docker with Strapi as the backend, a ECONNREFUSED error is encountered while attempting to fetch data in Next

Hello everyone! I recently created a simple Next.js page to fetch data from Strapi using an API. Everything runs smoothly when testing locally, but I encountered an ECONNREFUSED error when attempting to run the application in Docker. Here is the specific ...

Ways to compel string type or disregard type?

When using the following code snippet: <Image src={user?.profilePictureUrl} alt={user?.name} /> An error is encountered: Type 'string | null | undefined' is not assignable to type 'string | StaticImport'. Type 'undefined ...

Error: The localStorage object is not defined within the context of a Next.js application

I am developing a Next.js application Here is an example of one of my pages/components: import React from "react"; import { SomeLocalStorageComponent } from "some-external-lib"; const MyComponent = () => { const isBrowser = typeof ...

Unraveling the mystery of NextJS dynamic routing with slugs

Hey there! I'm currently working on a project using Next.js and I could use some help. Here's how I've structured my site: pages [slug] index.jsx index.jsx In the slug/index file, I have the following code snippet: export async ...

Increasing the maximum width of an image in CSS is necessary to see the max-height take effect

Within my HTML structure: <Col md="6"> <div className="hero-section"> <div className={`flipper ${isFlipping ? "isFlipping" : ""}`}> <div className="front"> <div className="hero-section-content"> ...

Create a flexible framework for extracting data from online sources

Currently, I am facing a situation where my server receives requests and I need a way to initiate the scraping process on a separate resource that is dynamically created. I would prefer not to conduct the scraping on my primary instance to prevent overload ...

Encountering 404 error when refreshing page on NextJS static site deployed on S3

I recently set up a static NextJS website on Amazon S3. Everything seems to be working smoothly, except for one issue. When the homepage loads and then users navigate to other pages using the navigation menu, there are no problems. However, if a user tries ...

Is there a way for my React application to detect changes in an npm package?

I am currently customizing an npm package for my application, but I am facing issues with it not being detected when starting my development server. Previously, I was able to resolve this by removing the library and reinstalling it, followed by replacing t ...

"Learn the step-by-step process of integrating Vendure (headless commerce) with Strapi CMS on Heroku for seamless deployment

Seeking guidance for deploying a webapp on Heroku with a unique tech stack: Frontend: NextJS (deployed on Vercel) CMS: Strapi (deployed on Heroku) Interested in adding a webshop using the Vercel/commerce example (https://github.com/vercel/commerce) and V ...

Ensure the parent container is filled and decrease the image resolution using next/image

I'm struggling to fit a high-resolution image into a fixed-size container. Using `layout="fill"` works well, but the original image downloaded is much larger than needed for a 125x125 container. Switching to `layout="fixed"` gives me a smaller file si ...