DEV Community

loading...
Cover image for Creating API Routes in a Nuxt App

Creating API Routes in a Nuxt App

Nader Dabit
Web and mobile developer specializing in cross-platform, cloud-enabled, and Web3 application development.
・2 min read

As a Next.js user, one of the things I've been used to working with were built-in API routes. When I tried out Nuxt, I was curious how I would achieve the same functionality.

In this post, I'll walk through how to easily create API routes in a Nuxt app using Express.

Implementation

To get started, start with an existing Nuxt app or create a new one using npx:

npx create-nuxt-app nuxt-with-api

cd nuxt-with-api
Enter fullscreen mode Exit fullscreen mode

Next, install express:

npm install express
Enter fullscreen mode Exit fullscreen mode

Next, update nuxt.config.js to add the following serverMiddleware configuration to specify the directory of the API routes:

serverMiddleware: {
  '/api': '~/api'
}
Enter fullscreen mode Exit fullscreen mode

Next, create a folder called api., and within the api folder create a file called index.js and a file called hello.js:

Next, open api/index.js and add the following code to configure the entry point to the express server:

const express = require('express')
const app = express()

const hello = require('./hello')
app.use(hello)

if (require.main === module) {
  const port = 3001
  app.listen(port, () => {
    console.log(`API server listening on port ${port}`)
  })
}

module.exports = app
Enter fullscreen mode Exit fullscreen mode

Next, open api/hello.js and add the following code to create a /hello route:

const { Router } = require('express')
const router = Router()

router.use('/hello', (req, res) => {
  res.end('Hello world!')
})

module.exports = router
Enter fullscreen mode Exit fullscreen mode

Next, test it out by running npm run dev.

Now, navigate to http://localhost:3000/api/hello and you should see your API response!

Conclusion

Creating API routes in a Nuxt app is more work than with Next.js, but servermiddleware allows you to implement your own API route setup fairly easily.


Cover image by Diego PH

Discussion (3)

Collapse
eostrom profile image
Erik Ostrom

Would you explain the if block in index.js? Thanks.

Collapse
davleda profile image
Dav Leda

I think you meant res.send('Hello world!'), not res.end

Also, please explain what the if (require.main === module) statement is for. I've never seen that in ExpressJS. Thanks.

Collapse
aacassandra profile image
Alauddin Afif Cassandra

works! but, when im deploying to vercel, im getting
502: BAD_GATEWAY
Code: NO_RESPONSE_FROM_FUNCTION
can you helpme?