Nuxt Server API Routes — Transcript

Transcript of the free Vue.js lesson Nuxt Server API Routeswatch the video lesson.

One of my favorite new features of Nuxt three is the ability to easily add API endpoints. Let me show you how to do that in this lesson. Just like a lot of the other special file types that we've created, we can create these endpoints with a Nuxty command. This time, we want to add an API endpoint.

And that's mapped to the command API. We're not going to do anything really special here, so I'll just call our endpoint hello world. This generates a new directory for us called server. ts.

Notice here that we've got a function exported now called define event handler. This is the function you'll always use when defining any of these server API endpoints. Then whatever is returned from this function will be the response sent to the browser. Let's test it out now.

In the browser, I'll visit slash API slash hello world. And sure enough, we get our message. If I check things out in the network tab and give the page a refresh, you'll see that our hello world file is of the content type text HTML. So these API endpoints are smart and will automatically pick the correct content type depending on what you return.

Since we've returned just text, it's an HTML content type. If we were to return a JavaScript object, what content type do you think we might get instead? Well, let's give it a try. This time, the content type is application JSON.

Pretty sweet, right? This is typically how you're going to handle your API endpoints. That is, you're usually going to return JSON, but we don't have to manually stringify it. Instead, we just return the proper JavaScript, and the Nuxt engine will handle the rest for us.

When I say Nuxt engine, that's actually not quite right. Under the hood, Nuxt is using a piece of software called Nitro and a server engine called H three to actually power these API routes. Inside of the documentation for H three, you can see a number of different helper functions that we can utilize in order to get more information about the request. As an example, we could get the request method with the get method function.

It's worth noting that most of these helper functions are going to require that you pass the event given to the event handler. This time visiting gives us the message get hello world. Another handy helper function is the get query function. This allows us to read the query string and the URL as a JavaScript object.

Let's remove the hello world here, append it to the end. And then in the browser, let's update our URL to include some query variables. We'll say hello equals world and color equals blue. And the result is, in fact, those query variables as an object.

In conclusion, if you really want to get the most out of these API routes in Nuxt, it's worth familiarizing yourself with Nitro and the H three server engine. I've left links to the docs for each of these in the description below.