Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serving next.js static assets from public folder after building time problems

Tags:

nginx

next.js

I'm working on a nextjs application that should be deployed in a LAN, and the server is not connected to the internet. So the problem that I have is that in the backoffice I've got some forms to add/update/delete employees informations. There are also images profiles and QRCode that are generated for some reasons. I store those images inside users_images folder inside the next.js public folder. In development everything works just fine I can server those static files(images). But when I execute next build and run the application for production,only images in the users_images are build time are serverd but the news assets that are being created in the backoffice are not served and the server returns 404.I've read in the nextjs docs and that is the expected behavior : Static File Serving.

As the application will be deployed in an offline server, I cannot use services like AWS s3 or services such as cloudinary for storing and retrieving images. Do you have any ideas about how to solve this problem to help me serve those files even after build?

I've also tried serving them with nginx and images are accessible but I get 505 while accessing pages. Here is my nginx configuration.

Next application listen on port 3000

server{
   listen 3000;
   root /path_to_apps_public_folder;
   location /{
       try_files $uri $uri/ =404;
    } 
} 
like image 449
Christian Lisangola Avatar asked Oct 19 '25 05:10

Christian Lisangola


1 Answers

Now I know you run the Next.js server at production, not building the static files and run as a client-side rendering app.

Look at your nginx config, it only serves static files (public folder, _next folder), you should add a proxy_pass to your Next.js server to handle other request (page requests, api routes...)

I rarely use nginx's root, because I know Next.js only have two static folders: public's subfolders (usually "static", put at public/static), and _next

server{
   listen 3000;
   
    
   location ^~ /static/ {
        alias /usr/src/app/public/static/;
        sendfile           on;
        sendfile_max_chunk 1m;
    }

    location ^~ /_next/ {
        alias /usr/src/app/_next/;
        sendfile           on;
        sendfile_max_chunk 1m;
    }

    location / {
        proxy_pass      http://<host_to_next_js>:<port>;
    }
} 

You can search around for the example configuration of Nginx + Next.js (https://steveholgado.com/nginx-for-nextjs/#final-nginx-configuration)

like image 73
nghiaht Avatar answered Oct 22 '25 04:10

nghiaht



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!