10

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?

Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57
Rafat Rashid
  • 191
  • 2
  • 10

2 Answers2

9

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

Frosty
  • 299
  • 5
  • 31
  • This is only applicable for apps that is not dynamic or does not have a lot of SSR from requests. https://stackoverflow.com/questions/61724368/what-is-the-difference-between-next-export-and-next-build-in-next-js – Bon Andre Opina Oct 04 '22 at 14:32
  • @BonAndreOpina if all your server requests are to the Laravel API it is 100% applicable. – Frosty Nov 23 '22 at 10:10
0

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.

Rafat Rashid
  • 191
  • 2
  • 10