Issue with Nginx causing 404 errors on NextJs API routes

I encountered a problem with my NextJs API returning a 404 error during a page reload in production when executed from getInitialProps.

The error message in my PM2 logs indicated that the 404 not found response was coming from Nginx.

It appears that NGINX is unable to recognize my routes in /api/*.

This issue does not occur locally, leading me to suspect a configuration or setup oversight in nginx.

Current versions in use:

  1. NextJs: 9.4.0
  2. nginx/1.18.0 (Ubuntu) - On AWS EC2

UPDATE

The problem seems to be related to an SSL issue, as disabling SSL in the nginx.conf file allows the APIs to function properly. However, a solution has yet to be found for this.

nginx config file

[nginx configuration code here]

Sample of NextJs getInitialProps code

[getInitialProps code sample here]

Sample of /api/employer/profile endpoint code

[endpoint code sample here]

PM2 Log Error Image: https://i.stack.imgur.com/dVPG8.png

Answer №1

SOLVED

It appears that the problem stems from nginx redirecting server requests from http to https, causing NextJs to struggle in identifying routes when they are in https, leading to Nginx returning a 404 error.

The solution lies in allowing a proxy pass for localhost to preserve requests at port 80 instead of automatically forwarding all port 80 requests to 443.

server_block conf

# redirect http to https
server {
  listen 80;
  listen [::]:80;
  server_name 127.0.0.1 localhost;
  
  location / {
          proxy_pass http://localhost:3000;
          proxy_http_version 1.1;
          proxy_set_header Upgrade $http_upgrade;
          proxy_set_header Connection 'upgrade';
          proxy_set_header Host $host;
          proxy_cache_bypass $http_upgrade;
      } 
}

server {
  listen 80 default_server;
  listen [::]:80 default_server;
  server_name yourserver.com www.yourserver.com;
  return 301 https://$server_name$request_uri;

}

server {
  # listen on *:443 -> ssl;
  listen 443 ssl default_server;
  listen [::]:443 ssl default_server;

  server_name yourserver.com;
  
  ssl_certificate /etc/letsencrypt/live/yourserver.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/yourserver.com/privkey.pem; # managed by Certbot
    ssl_session_cache builtin:1000 shared:SSL:10m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_ciphers HIGH:!aNULL:!eNULL:!EXPORT:!CAMELIA:!DES:!MD5:!PSK:!RC4;
    ssl_prefer_server_ciphers on;

  location / {
    # reverse proxy for next server
    proxy_pass http://localhost:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
  
    proxy_read_timeout 300s;
    proxy_connect_timeout 75s;

    # we need to remove this 404 handling
    # because next's _next folder and own handling
    # try_files $uri $uri/ =404;
  }
  
  location ~ /.well-known {
    allow all;
  }
}

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

Next.js facing an issue with CartContextProvider resulting in a blank page being displayed

Working on implementing the shopping cart functionality in Next.js, I am facing a challenge. When I call CartContextProvider in _app.js, it seems to result in an empty page. Any insights from reviewing the code would be greatly appreciated. Thank you. _ap ...

Dynamic routing in Next.js expands upon the current path

With my Next.js blog utilizing Strapi CMS, I am attempting to arrange the posts by their respective categories. I have set up a dynamic route for categories [id].js and have implemented getStaticPaths as shown below: export async function getStaticPaths() ...

Having trouble saving a JSON object as a cookie in Next.js using js-cookie

I am having trouble setting user data along with a token ID in a Cookie. The token is set correctly and appears in the console.log output, but my user JSON object is not being properly set and only shows as "object Object" in the Cookies. However ...

Obtaining information from a intricate string input

{JSON.stringify(walletData.transactions, null, 2)} My goal is to extract backend data and display it as a table. The response has been converted into an array as shown below. [ { "date": "Nov 07, 2023", "description" ...

Shallow routing in Next/Link allows for the refreshing of the page when a

My inquiry pertains to the usage of a Link: <Link href={href} passHref shallow> <StyledLink $active={active} $disabled={disabled} onClick={() => passBackNumber(number)} > {number} </Styled ...

Confused about the concept of an SWR subscription

As I navigate through SWR's various features, there is one that has caught my attention: SWR-subscription. The concept of "subscribing to real-time data sources with SWR" is unfamiliar to me and I am seeking an explanation along with a straightforward ...

The Algolia Hit Component is having difficulty functioning properly within a grid layout

I am in the process of converting my next API to an Algolia search. The Hit component is a single component that renders for each record. However, I am facing an issue with implementing a grid layout. Below is the code snippet from before (which was workin ...

Preventing NextJS Link Component from Displaying 404 Error

Hey there, can anyone help me figure out why my Link Component is having trouble finding the linked page? It's weird because VSCode is auto-completing the file name as I type it in, but all I get is a 404 error. //index.js in WelcomePage folder import ...

External API data is shown in the browser console but appears as undefined on the page

Can you please lend me a helping hand? I am facing a critical issue while attempting to retrieve data from an external API using axios in NextJS (Reactjs)/TypeScript through getServerSideProps. The data fetching is successful, and the JSON is returned on t ...

How can I implement a popup overlay on a redirected URL in Next.js?

Currently in the process of developing my own URL shortener, I'm looking to incorporate a Call To Action on the target URLs page. My tech stack includes NextJs, Tailwind, NodeJs, and Express. Something along these lines: example image If anyone has ...

What is the best way to host a Next.js App on Netlify?

I've encountered a problem with my Next.js app deployment. Following a tutorial from netlify's blog on implementing Server-side Rendering for Next.js using netlify, I managed to build the app successfully but it's not functioning as expected ...

Next.js API route is showing an error stating that the body exceeds the 1mb limit

I'm having trouble using FormData on Next.js to upload an image to the server as I keep getting this error. I've tried various solutions but haven't been able to resolve it yet. This is my code: const changeValue = (e) => { if (e.target ...

Is there a way to make an accordion close from a nested component in react?

I'm in the process of developing a page to update product information on an e-commerce platform using NextJS. On the individual item page, I have structured the image upload section within an accordion. After the images are uploaded, I want to reset t ...

Guide to implementing Apollo GraphQL subscriptions in NextJS on the client-side

As a newcomer to NextJS, I am facing the challenge of displaying real-time data fetched from a Hasura GraphQL backend on a page. In previous non-NextJS applications, I successfully utilized GraphQL subscriptions with the Apollo client library which levera ...

Why do I keep receiving a code parameter in the URL when using NextAuth with Patreon?

When using NextAuth with Patreon, I encountered an issue where after allowing access, I was redirected back to my URL with the "code" added as a parameter in the URL. From my understanding, NextAuth should handle this process automatically by passing the c ...

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 ...

What are some strategies to enhance the build performance of nextjs in development mode?

I am currently working on a small Next.js application that uses both internal and external libraries. While the production build performs well, I have noticed that the development builds are extremely slow. Whenever I make a change to a page component that ...

How can I ensure server-side rendering for every request in NextJS deployed on Vercel platform?

When working with Next 13 deployed to Vercel, I encountered an issue where calling an API server-side using a vendor library resulted in Vercel not recognizing that a fetch was happening, thus generating a static page. Is there a way to ensure the page is ...

Encountering issues with accessing image files located in the public folder of my Next.js project - Receiving a 404 Error message

I am currently facing an issue with my Next.js project where I am unable to use image files from the public folder. Despite checking that the file paths, names, and extensions are correct, as well as ensuring my configurations are accurate, I keep encounte ...

Exploring nested arrays of objects and applying value constraints

Is there a way to iterate through an array and display only 5 items at once, with the option to call a function on click that will add another 20 items? I have an object structured like this: let someObject = [ { data: [ { id: 123, ...