DEV Community

Cover image for How to Make Full-Stack Project with Nuxt and ExpressJs
Abdallah hamouda
Abdallah hamouda

Posted on

How to Make Full-Stack Project with Nuxt and ExpressJs

Introduction

Before I knew this I was making the backend and the front-end separately and the cors handle all the cross-origin requests,
But here is the problem cause I am broke I can't afford to pay for a good server then I went with Heroku,
and the free plan has a sleeping time when the server isn't used they shut it down and rerun it when somebody uses it then the whole npm run this is a lot of time to wait for the user,
so I decided to go with the same origin to cut this downtime to half then I made my research and I didn't found a lot so I decided to make one for me and the people beginners like me
let's start
If you wanna make the backend and the frontend of the same origin you can do it in two ways

From Nuxt Docs

here basically you write a regular express app

const app = require('express')() 
Enter fullscreen mode Exit fullscreen mode

then identify your port the server will run on

const port = process.env.PORT || 3000
Enter fullscreen mode Exit fullscreen mode

then you load nuxt and write a line of code to check are you in development or not

const { loadNuxt, build } = require('nuxt');
const isDev = process.env.NODE_ENV !== 'production'
Enter fullscreen mode Exit fullscreen mode

then we make async function then use nuxt.render middleware

async function start(){

 // Render every route with Nuxt.js
 const nuxt = await loadNuxt(isDev ? 'dev' : 'start')

 //render Routes with nuxt render
 app.use(nuxt.render)

//build on dev mode because of hot reloading (reload the page when any change happens)
 if(isDev){
 build(nuxt)
 }

 //listen to port
 app.listen(port, '0.0.0.0')
 console.log("loading on "+ port)
}
start();
Enter fullscreen mode Exit fullscreen mode

then go to nuxt.config.js

middleware:['name of your middleware']
Enter fullscreen mode Exit fullscreen mode

if you are interested to use this method
you can read more on
Nuxt Docs

Server Middleware

this is the simpler way to do it you have to do three things
1- Make api file and put all your express code on it
2- add this to the end of your index.js code

module.exports = app

// Start standalone server if directly running

if (require.main === module) {

const port = process.env.PORT || 3001

app.listen(port, () => {

// eslint-disable-next-line no-console

console.log(`API server listening on port ${port}`)

})

}
Enter fullscreen mode Exit fullscreen mode

3- add serverMiddleware to nuxt.config.js

serverMiddleware: {

'/api': '~/api'

},
Enter fullscreen mode Exit fullscreen mode

if you wanna use it directly without doing anything there is a ready to use the template on GitHub

in the last thanks for reading, I hope you found this helpful for you,
if you want me for work you can DM me on any of my social media on my profile

Check my new Startup Dremor

Top comments (0)