Logo

dev-resources.site

for different kinds of informations.

Run NextJS App in shared-hosting cPanel domain!

Published at
1/14/2025
Categories
nextjs
cpanel
node
namecheap
Author
saad4software
Categories
4 categories in total
nextjs
open
cpanel
open
node
open
namecheap
open
Author
13 person written this
saad4software
open
Run NextJS App in shared-hosting cPanel domain!

Have you ever tried to run a NextJS web app with a shared-hosting account? it is not a straightforward operation! and in my experience with Namecheap shared-hosting account not a good idea either. shared hosting account doesn't offer enough resources for NextJS apps which suffocates the web app ๐Ÿ˜ฎโ€๐Ÿ’จ. You will find it tooooooooo slow, so avoid doing so if possible. Yet, sometimes staging servers are okay to be slow and we need to do the implementation anyway ๐Ÿ˜…. if this is your case, or you don't have other choices for now, then stay with me!

We will cover

  • best practices to avoid limited resources issues
  • Step-by-step guide to setup the NodeJS app
  • NextJS app config file initiation

Build the app! ๐Ÿ‘ท

We will work on the latest version of NextJS I have, NextJS 14.2.3, I have also tried this on NextJS 13.x and it worked well. Assuming our NextJS project is ready to be deployed, make sure to build the project locally, shared-hosting servers don't have the resources to build a web project (or at least Namecheap shared hosting doesn't). To build the project, issue

npm run build
Enter fullscreen mode Exit fullscreen mode

or use yum build if preferable, but make sure to build the project!

Clean the app ๐Ÿงผ

Usually, small to medium apps size about 800MB, which is huge! To avoid uploading this huge size to the server, we can clean the app locally by removing some folders, but before doing that, I suggest keeping a copy of the old project to avoid losing the development file in case you decide to continue working the project later. now in the copy folder, you can

  • remove the node_modules folder, we can install it later on the server
  • remove all contents of .next/cache/ folder, those are temporary data used during building, but they can be huge! so make sure to remove them. if you cannot see the .next folder, try showing hidden files (try command+shift+. in Mac)
  • remove git data; make sure to remove .git folder, since we have already shown hidden files it should be visible now. (don't do this in the original project folder)
  • Actually, after building the project, you can remove all page code folders since their code is already generated in the .next folder, but their size usually is not that big, so it is okay to keep them.
  • *Don't remove public or assets folder โš ๏ธ

after cleaning the code, compressing the next cleaned code should result in about 2MB to 5MB zip file, which we can upload easily

Setup NodeJS app in cPanel ๐Ÿค“

Usually, NodeJS app appears in the software section

cPanel NodeJS

If you cannot find it there, make sure to ask the support to point it out or install it if possible

after opening it, we can create a web app by clicking CREATE APPLICATION

Create Application

After selecting the domain or subdomain you want to attach the web app with, and the app folder, make sure to select the latest Node.js version and hit the CREATE button

Create app

After creating the NodeJS app, opening the app URL should show a message that an app was created successfully

It works!

NodeJS 22.8.0
Enter fullscreen mode Exit fullscreen mode

and we should be able to find .htaccess and app.js files in the site folder

app folder

all other folders are not required for our NextJS app and can be removed safely.

Uploading app files

After cleaning unnecessary files, the easiest way to upload app files is by using the file manager

File manager

after uploading the zip file, we can unzip it by right-clicking on it and choosing the Extract option, then move the extracted files to have the next config file in the same level as app.js

app files

Install app packages

it is time to install packages, we can either install them from the cPanel UI, by opening the NodeJS apps, choosing to edit our app, and hitting "Run NPM install" button in the UI

Edit app

Install packages

it could take some time, normally a green toast will appear on the top-right edge of the browser informing you of the operation success, or we can install the packages using SSH terminal or online terminal at cPanel, just make sure to use the provided virtual environment command

virtual environment

then simply run npm install, either way you choose, make sure **NOT** to issuenpm run dev` on the server, since it may affect the built files. if you have already done so, you may have to upload the locally built files again.

Update app.js file

We are almost done! just update app.js contents

`
const { createServer } = require('http')
const { parse } = require('url')
const next = require('next')

const dev = process.env.NODE_ENV !== 'production'
const hostname = 'localhost'
const port = process.env.PORT || 3000

const app = next({ dev, hostname, port })
const handle = app.getRequestHandler()

app.prepare().then(() => {
createServer(async (req, res) => {
try {
const parsedUrl = parse(req.url, true)
const { pathname, query } = parsedUrl

  if (pathname === '/a') {
    await app.render(req, res, '/a', query)
  } else if (pathname === '/b') {
    await app.render(req, res, '/b', query)
  } else {
    await handle(req, res, parsedUrl)
  }
} catch (err) {
  console.error('Error occurred handling', req.url, err)
  res.statusCode = 500
  res.end('internal server error')
}
Enter fullscreen mode Exit fullscreen mode

}).listen(port, (err) => {
if (err) throw err
console.log(> Ready on http://${hostname}:${port})
})
})

`

We are done! you may need to reload the NodeJS app though ...

Restart the app

are you interested in more cPanel-related topics? then

Stay tuned ๐Ÿ˜Ž

node Article's
30 articles in total
Favicon
Breaking the Scale Barrier: 1 Million Messages with NodeJS and Kafka
Favicon
assert in Nodejs and its usage in Grida source code
Favicon
Understanding Node.js Cluster: The Core Concepts
Favicon
๐ŸŒŸ A New Adventure Begins! ๐Ÿ›ต๐Ÿ•
Favicon
How โ€œSilicon Valleyโ€ Inspired Me to Create a Photo Compressor CLI for Web Developers
Favicon
How Does This Jewelry Customization Site Work? Need Insights!
Favicon
Building a Secure Authentication API with TypeScript, Node.js, and MongoDB
Favicon
Understanding OAuth 1.0a Signature Generation: Postman vs. Node.js Library and Custom Implementation
Favicon
How to Fix the โ€œRecord to Delete Does Not Existโ€ Error in Prisma
Favicon
[Boost]
Favicon
Run NextJS App in shared-hosting cPanel domain!
Favicon
Construindo uma API segura e eficiente com @fastify/jwt e @fastify/mongodb
Favicon
New ways to engage with the stdlib community!
Favicon
Sore Throat: Causes, Symptoms, and Treatment
Favicon
Back to MonDEV 2025
Favicon
๐ŸŒŸ How to Fix Node.js Path Issues in VS Code (Step-by-Step Guide)
Favicon
How to write unit tests and E2E tests for NestJS applications
Favicon
Cookies auto clearing after browser refresh issue , CORS related express cookies issue
Favicon
Exploring TypeScript Support in Node.jsย v23.6.0
Favicon
Mastering Backend Node.js Folder Structure, A Beginnerโ€™s Guide
Favicon
how to setup express api from scratch
Favicon
Load Balancing Node.js Applications with Nginx Upstream Configuration
Favicon
Using LRU Cache in Node.js and TypeScript
Favicon
Welcome to Siitecch! Your Go-To Platform for Beginner-Friendly Full-Stack JavaScript Learning.
Favicon
I Really like Middleware in NodeJs/Express.
Favicon
Your own Telegram bot on NodeJS with TypeScript, Telegraf and Fastify (Part 3)
Favicon
Understanding Node.js Cluster: The Core Concepts
Favicon
JWT Authentication With NodeJS
Favicon
Stream de Arquivo PDF ou Imagem S3 - AWS
Favicon
Understanding Node.js Alpine Versions: A Lightweight Choice for Your Projects

Featured ones: