Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deploy Next.js app without Node.js server?

I was hoping to deploy a Next.js app with Laravel API. I had developed React apps with CRA and in those I used the API server to serve the index.html of the CRA as the entry point of the app.

But in Next.js, after development I get to know that it needs a Node.js server to serve (which is my bad, didn't notice that). There is an option next export that builds a static representation of the Next.js app and it has an index.html. I am serving the index.html as the entry of the app by my Laravel API. It is serving the page, but just some of the static contents.

What I was hoping to know is it possible to host the aPI and the Next app from a single PHP shared hosting without any node server? If so, how? If not so, what could be the alternatives?

like image 404
Rafat Rashid Avatar asked Nov 07 '22 03:11

Rafat Rashid


2 Answers

Apparently there is no alternative to nodejs server, which is not an option for me currently, so I unfortunately had to abandon next.js and create a CRA app and used as much from the next.js as I could.

like image 39
Rafat Rashid Avatar answered Nov 14 '22 09:11

Rafat Rashid


Actually the acepted answer is completly wrong, when you do yarn build and in your package.json is set like "build": "next build && next export", you will get an out folder which all the items in there are used to build without node.js server

Now since you are using laravel, and you use the out folder you will only load half of the page because the routes are not set properly. for that to work you need to edit your next.config.js edit it to

module.exports = {
 distDir: '/resources/views',
 assetPrefix: '/resources/views',
}

These will set the root directory to the root one in Laravel. now this will work for SPA (single page application) only for the dynamic routes you need to match with a view file for each one that you have in your out folder

For each route that you have you need to create a new "get" route in laravel

Route::get('/', function () {
  return require resource_path('views/index.html');
});

Route::get('/contacts', function () {
  return require resource_path('views/contacts.html');
});

Route::get('/post/{slug}', function () {
  return require resource_path('views/post/[slug].html');
});

Notice that you can pass a wildcard for dynamic routes and they are all gonna work. once you do that and you deploy route out folder inside /resources/views in Laravel it's going to work

like image 125
Frosty Avatar answered Nov 14 '22 07:11

Frosty