Syntax Video
Nuxt Crash Course 2025
- 0:00 intro
- 0:58 tour of the docs
- 3:38 nuxt modules
- 4:19 generate a nuxt app
- 6:14 eslint stylistic setup
- 8:42 vscode editor settings
- 9:46 setup picocss
- 10:27 layouts
- 11:32 pages
- 12:13 components
- 13:26 NuxtLink
- 14:41 rendering
- 15:11 api routes
- 16:56 useFetch
- 20:02 useFetch lazy
- 22:07 sending api errors
- 24:03 db setup overview
- 25:38 insert task
- 26:32 readValidatedBody
- 28:25 $fetch
- 33:08 insert task
- 33:34 route params
- 35:06 display single task
- 35:35 getValidatedRouterParam
- 36:20 find first task with id
- 37:15 useRoute
- 37:38 list single task
- 39:23 homework
- 40:00 thanks!
intro
Next is the progressive web framework. It's built on top of Vue.js and it's a meta framework. So it allows you to build server rendered applications, client rendered applications, content driven applications. It allows you to build out API routes and a whole lot more. And in this video, I'm going to give you a whirlwind tour of how you can get up and going with Nux. Now, this is going to be fairly introductory to kind of just acquaint you with what it's like working inside of a Nux application. I have a much more in-depth course that's coming soon here on the channel. But for now, we can learn the basics of Nux by building a full stack application that talks to a SQLite database to manage tasks. So this one app demonstrates things like layouts, pages, use fetch and async data, serverside rendering, client side rendering, loading state, and all the stuff in between. So if all of that sounds good to you, let's dive in to next. My name is CJ. Welcome to syntax. First, let's take a tour of the
tour of the docs
Nux website. So, you can see on the homepage, they kind of show you all the stuff that it can do. First up, it doesn't take much to get going with a Nux app. If you know Vue.js, you can already create a basic Nux app. From there, they have file system routing. So, any page that you want to create, you just create a separate view file and that will automatically route to that file. Next up, they have built-in data fetching which allow you to request content internally or API endpoints. It also has autoimp imports, so you can define components or composables and then automatically use those in any of your components without having to import them in. And of course, you can define API routes. And this is powered by Nitro under the hood. So, it has everything you need to build a full stack application. Now, let's take a quick tour of all the docs that they have available because they're really good and there's a lot of them. So, first up, there's the getting started. And this kind of just walks you through at a high level all of the various parts and pieces of Nux. We're going to dive into a lot of these and actually show some examples of how they work, but this is definitely if you're brand new to Nux, I would recommend you just go through this and kind of see all the things available
to you from there. If you check out the guide, this one kind of just breaks down all the key concepts you're going to be using. But a really useful one is the directory structure section. So a Nux app actually has these conventions where if you put things in these specific folders, stuff will happen automatically and Nux can handle a lot of things for you. So we already saw content and composables, but there's also layouts.
So you can define layouts for your app. You can define middlewares. You can also create your own custom plugins. If you have code that's reusable throughout your app, you could put it in the use hills folder. And then any of the files you can see at the root are documented here. So you can click on them. It's going to show you lots of info about them. And for any of the folders, that's going to show you all the kinds of things you can do in that folder. So, this is where I spend most of my time whenever I'm in the Nux docs because it really breaks down what you can do in each of those areas. Another spot is the API docs. And really, these are just all of the globally available components and composables that you have access to when you're working inside of Nux. Really, I just come to this section of the docs if I've figured out what I need to do, but maybe I need to dive a bit deeper into how one of these specific composables or components works. This is a good spot for that. And then they also have examples for all the kinds of things that you would want to do. They have examples showing how the autoimp imports work and data fetching and state management and the layouts and then talking about various ways to do routing and also like more advanced setup. So this is a good spot if you just want to see some implementations of these various features that are talked about throughout the docs. And then finally
there's the community tab. So they have a very active discussion board on the NX GitHub repo. They also have a discord that you can join and ask questions in. And so this section just breaks all of that down. So their docs are awesome. I highly recommend you start there. Pretty much everything I've wanted to know about Nux I was able to find in the docs. So definitely check them out. Next up is integrations. And once we start building an app, I'll show you how we can install some of these modules. But this is one of the other great things about the Nux ecosystem is someone has built a module for one of the many things that you'd like to do. So for example, if you want to set up ESLint, there is a core module for automatically setting up ESLint. If you want to set up Tailwind, there is a Tailwind module. If you need access to icons, there's Nux icon. There's just a ton of these plugins. And what's great about them is once you install them, a lot of times they're zero config. You literally add the plugin to your config and then you're ready to start using that thing.
nuxt modules
So this is awesome because there's a lot of things that you don't want to have to set up manually every single time you're working on a NXT app. And chances are if there's something that you want to do, there's probably already a plugin that can handle it. So let's start building. If you head to the main page, they have a command that you can run and we can generate a NXT app. So I'll run this command in this directory. I am using PNPM, so I'm going to use PNPM create instead. Then we can give it a name. I'm going to call this my tasks app. And again, I use PNPM. And then here is another great part of their CLI. They instantly give you access to a lot of those plugins that I was showing you on their website. For our app, I'm just going to add ESLint. But as you can see, a lot of these are just one click away from installing and getting getting set up in your app. But we'll use the ESLint plugin because it comes preconfigured to work with ESLint inside of your Nux app.
generate a nuxt app
Now, let's open this up with VS Code and take a quick tour. So like I mentioned earlier, if you check the nu literally every single one of these files is described in this section under guide in the directory structure. So again, if there's something that I don't cover, you can head over to that section. But just at the top level, one of the main things here is our Nux config. So any of the plugins we installed are going to get listed out here. And then any configuration for those plugins or configuration for Nux is going to happen in this file as well. We of course have our ESLint file and you can see that it comes preconfigured with Nux. So, it's ready to go to start linting your view files. And then you can see our entry point, which is app.view. Now, these are just a couple of built-in components that actually don't exist in your codes anywhere here, but let's start up the NXT app so you can see what these give you. So, if you do a pmppm rundev, that'll start it up. Runs on port 3000 by default. And then if we open it up, we have ourselves a Nux app. And like I said, these are just default built-in components. We can get rid of these, add just a nice little hello world, and we have a completely bare app to get started building. we don't have to go in
and delete any of those example files. That's just something really nice that's built into the framework. Now, like I mentioned, Nux is built on top of Vue.js, so I'm not really going to focus on any of the Vue features. If you're interested in learning about Vue, check out the Vue crash course that I released a few weeks ago here on the channel. And I dive into like what is the template and how to set up your script and how to set up state and work with all the Vue directives and everything else. For this crash course, we're really just going to be focusing on the Nux features. Now, one of the first things I want to do is just slightly customize the ESLint config. And if you've been watching the channel long enough, you know that I I spend time doing this. Uh but this is actually very easy to do. So let's head to the docs for Nuxlint. And once you're on the site, it tells you all the different ways that you can configure it. But specifically, if we look at the ESLint stylistic section, this allows you to enable formatting via ESLint. Not going to get into if you should do this or not. You also could just use prettier, but I like the fact that this module is already set up to go with that. So we can actually add this section to our Nux config. So if I head to the Nux config, there is a section here for ESLint. And this is the other
eslint stylistic setup
nice thing about the Nux config. It has really good type completion. So once you've added a specific module, you're going to get all of its options here. But we want to add this ESLint section and enable stylistic. And then I can turn on all of my favorite formatting rules. So I can set semicolons to required. I can set quotes to be double quotes. And I can set comma dangle to whenever we have multi-line. And then also set indentation to use tabs. So, like I said, you could use prettier for all of these things, but I really like that the stylistic plugin is kind of just ready to go here with ESLint. So, let's actually set up a lint task. If we head to our package.json, set up a lint.
We can just say eslint in the current directory. So, let's run the llinter. And we should see some issues once this config has kicked in because you'll notice I'm using single quotes here, but I told it that it should be using double. So, I'm actually going to restart my nux. So, that way it picks up that config for eslint. And then in another tab, if I do pnpm lint, that will run the llinter and we should see some issues. Yeah, look at that. So all of these stylistic issues. But the nice thing about stylistic issues is they're autofixable. So I'm also going to add a fix command here. So we'll call this lint fix. And we'll just run eslint with the d-fix. And now if we run pnpm lint fix, that should fix all the fixable issues. But we still have one more define nux config is not defined. So this is in our nux config. And if we reload VS Code, we should see that error in here too. And we do. Um, and I think this is actually because ESLint can't find our TypeScript dependency. So, we are using TypeScript, but if you look at our package.json, that dependency isn't at the top level. It's kind of hidden
behind next. So, I'm going to install that directly and see if it fixes it. So, we'll do a pmppmi capital D to add it as a dev dependency. And we'll add TypeScript. And now we'll try running that lint fix. There we go. And so, ESLint was able to integrate with TypeScript. And then we don't see that error anymore. And if we reload VS Code, we should be good to go. Awesome. Now, one more thing here. If we do have a stylistic lint error inside of the editor, it shows a red squiggly. And I actually don't want to see that because all of these stylistic errors are autofixable. So, I'm going to set up a VS Code settings file that doesn't show errors if they're autofixable. So, I'll create a folder called. VS Code. And then in here, we'll create our settings.json. And the first few settings we'll enable are to disable prettier because we're going to be using eslint stylistic to do all of our formatting. And then we're also going to set source fix all on save. So that way all fixable issues are automatically fixed whenever we save a file. Then to not show these red squigglies whenever it's just a stylistic error, we're going
vscode editor settings
to turn off some of these inside of the editor. So these I actually pulled from AntFu's uh VS Code settings that he has set up. I typically set up an app with AntFus ESLink config. But essentially, this just turns off those errors in the editor because they're autofixable. And when we save, they're going to autofix. So with those settings now, we don't see the red squiggly, but if I save the file, it automatically reformats it. So this is the editor experience that I prefer. Now let's get some styles going for our app. So I want to focus on NXT.
setup picocss
So we're not going to use Tailwind or anything else like that. I'm going to use Pico CSS because it just adds a bunch of default styles. So let's install it with PNPM. And now we can add it to our Nux app. So if we head over to the Nux config, there's a setting in here called CSS. And this allows us to add global CSS that will be added for any page. And you can also include the name of a node module. So if we add at pico CSS pico, that's going to automatically bring in that CSS on every page in our NXT app.
So if I save that, head back over, you'll see that we now have some nice default dark styles, and that's what you get with Pico CSS. Now let's talk about layouts and pages. So by default this app.view is our only entry point for our next app. If we create a layouts folder, this will get automatically picked up by next. And inside of here I can have a default view file and this will be our default layout. So I'll set up a template and this template will be used to render out our pages. So in Vue.js, you can have a slot inside of a component that basically tells it where something should render out. So essentially we want all of our pages to get rendered here and then we can define the default elements that should appear around them. So I'm going to first create a wrapper element and then let's add a navbar to our application. So if we look at Pico CSS, they do have some default styles for just navs. It's like a nice little nav bar up at the top. So let's add that here inside of our layout. And then we'll actually wrap that slot in a main element with a class of container. So that'll give it some nice breathing room on the edges. And then we'll also make our nav a class of container. And now we actually want to
layouts
use this layout. So inside of app.view view. Instead of all this, we'll bring in the next layout component. So, this is built in to next. And essentially, we'll find that default layout and render it out here. And then to tell it what to render into that slot, we can use the next page component, which is also built in. And that will find any of our pages that we've created. Now, we don't have any pages, so let's create one. So, if we create a folder called pages, next will automatically look in here and try to find a page that matches the current route. So, if I create an index.view file, let's add our hello world inside of here. Now I have a page at the slash route that when my next app loads up, next page is going to kick in.
pages
It's going to see that we want to render that layout. It'll pull that layout in. It sees that we want to render the page here. So it'll read this page in and we should be good to go. So now you'll see that we have a nice little navbar and we have that page being rendered in here. So that's looking great. Now let's actually work on some custom components. So one of the cool things about Next is you can also have a components folder where things get autoimpported. So I'm going to create a components folder.
components
Inside of there, let's create a component for our navbar. So one thing I'll do is actually first create a folder called app. And every component inside of this app folder will now be prefixed with the word app. So if I create a component in here called navbar view, this will actually be called app navbar. So prefixing your components is typically something you want to do, especially when you have a lot of components and components that have a generic name like navbar. You want to know that these are coming from your app. But it's really nice that you can just put them into nested folders and not have to have a bunch of app dash all over this folder. So in here, I actually want to extract out this nav. We'll add our template, throw the nav in there, and then inside of our layout, we can access it. And you'll notice we get autocomplete. So it's like, hey, I know about that app navbar. And then we'll bring that in here. And if we refresh the page, should look exactly the same, but now we've got that autoimp importing and defined in our components folder. So for this, we're going to be building a tasks app. So let's update the title and then we'll update the links here. So I'm actually going to have a page called
create task and that will be the one link in the top bar area. And in order to link to it, we should use the next link component. So this is another built-in component to next. And essentially allows us to link to the pages that we have internally. So here I'm going to say this should go to and you can pass in just a direct URL. So let's say we create a page at /create.
NuxtLink
You can do it like that. You can also use object syntax. So we can bind this and say that this should go to the route with the name create. So this is nice especially if you have more complex routes. You don't want to have to construct that URL with just a string. You can use this object syntax. And for this to actually match a page, we need a page called create. So let's create a new file in here called create. Give it a template and then give it a title that just says create a task. And now when I click this link, it'll take me to the create page. So let's give it a try.
Click here, create a task. And then let's make it so that we can click the title to take us back to the homepage. So we'll also make this a nux link. And in this case, I will just use the URL because slash is easier to write than an object. But now this will take us back to the homepage. And this takes us to the task page. So as you can see, the routing system inside of Nux is pretty intuitive. Essentially just create your pages here. They get automatically rendered in and then you can use Nux link to link between them. Now to talk about how all of this is working.
rendering
Essentially whenever we load the page for the first time this is actually a serverside render of the initial page and then once we start clicking around it's actually behaving as a single page application and you get all of that for free. It's just how a next app will behave once it's already been hydrated and loaded in. You of course have more fine grain control. So you can say that this page should be server rendered all the time and this page should always be client rendered. But if you don't want to specify that directly, you get a nice fast efficient behavior by default. So next up, let's actually list some tasks on the homepage here. And to do this, we're going to create an API endpoint.
api routes
So if you head into the server folder, this is where you can create your endpoints. And in here, I'll create a folder called API. And then inside of there, I'm going to create a tasks.get.ts file. So this server folder here is actually powered by Nitro which NXT is built on top of and essentially allows you to define API endpoints inside of this folder here. And if a file has a method name in it, it will respond to requests for that specific method. So right now this will respond to get requests on API/tasks. And in order to create an event handler, we need to export default define event handler. So this is globally available to us. It comes from H3 which is actually what Nitro is built on top of. So it's it's these Lego stacks. So H3 is the base web framework.
Nitro makes it nice and gives you file routing and a lot of other utilities. And then Nux is built on top of that to allow you to integrate with Vue and adds a bunch of other nicities on on top of that as well. So as you're working inside of Nux, when you're working in API routes, the Nitro docs are great and then especially the H3 docs because this will show you the more underlying utilities that you might need to access when you're working on API routes. A lot of that is documented in the Nux documentation, but if you ever find yourself trying to figure out what exactly is define event handler or what is this event context here, you might need to take a look at the H3 docs or the Nitro docs. So this is our event handler and for now I just want to return a static list of tasks. So I'm going to return an array. Each task will have an ID and a title. This will be learn next and then whether or not this task is done. So it'll start off as false. Let's just add like one more learn view. Okay. So we have this API handler that just returns a list of data. Now of course you could read from a database which we will do but I just
useFetch
want to show you really quick the kind of type completion that we get here. So I've defined my API endpoint this way. Let's say I want to request this data on the homepage here. We'll actually add a script. We'll set the language to TypeScript and we'll be using script setup. If you're completely new to Vue.js, JS definitely check out the crash course video that I created here on the channel because we'll kind of gloss over some of the view specific things and really just focus in on the nux things. But inside of our script here, we want to request that data when this page loads. So there's a built-in composable called use fetch. And this does lots and lots of stuff for us including making sure that this data gets requested on the server side also keeping that data reactive on the client side. And as you will see has full type completion. So it knows about all of the API routes that I've defined. So let's make a request to API tasks. And then that gives us back quite a few things.
One of them being the data itself. So what is returned from the endpoint. We also get access to the error if there was an error. And we get access to status. So if this request is happening on the client side, we can potentially show like a loading spinner. Now I actually can use the await keyword here. Typically inside of view components, you don't use the await keyword because this needs to be synchronous, but under the hood, this actually uses the suspense API. So when this page is rendering, this data is actually going to be requested on the server side and then rendered with that data. And then when the client hydrates, it's going to see that it already has that data and it won't need to make a request on the client side. But this gives us the data.
So let's just render it out. We'll have a top level element. I'm going to use an article element because Pico makes those show up as cards. And then for each of the tasks in data and let's actually rename data so it's clear. So this is tasks. So for each of the task in tasks we're going to render out the title. So right here I'll just have task.title.
And we do need to give this a key because view uses the virtual DOM. It needs to keep track of those. So like I mentioned if you're new to Vue and maybe you don't know what V4 is or binding of attributes or using handlebars, check out the crash course. I dive deep into what all that stuff is and explain all of that. But now when this page loads, we should have all of those tasks from our API and they get rendered out here.
So if we head back to the homepage, look at that. We've got learn next and learn view. So this use fetch is extremely powerful and I'll prove to you that this is actually serverside rendering. If we filter the network request to only show XHR and I request this page, you'll notice that the only XHR requests are for like internal dev things because I'm running the dev server. it doesn't actually make that request to load that list of tasks. But as I navigate around the app now that it has been initially serverside rendered, it will make that request on the client side. So if I go to the create page and then I head back to the homepage, you'll see that use fetch is smart enough to see, oh, I'm on the client side now. Let me make sure I have that latest data. And that actually does make an exhr request to get the list of tasks. Now, there's one other thing we need to take into account, and this is especially if you have like a slow API or maybe you're talking to a database and the queries take a little while because right now we're running in dev and this data just returns immediately and it's also just a static array. But what happens if this API
useFetch lazy
endpoint takes a long time? So, let's actually just wait for 2 seconds before returning the response. I'll make this async and then just wait for 2 seconds. And check this out. If we go directly to the app, it's waiting for that data to be resolved before it server renders the app. But when I'm running locally, I can head to another page. If you remember, when we head back to the index, it's going to make that request on the client side. But watch what happens. It doesn't go to that page until the data is available. And I've worked with other frameworks and it's not as easy to fix behavior like that. But in Nux, it's actually very easy. So if we head back to this use fetch, we can pass in an option. And if we say that this should be lazy now, it makes it so that it will navigate to the page and then we can get access to whether or not we're loading using the status. So with that one change once the app has initially rendered, I can navigate around and then if I head back to this page behind the scenes, it's actually re-requesting that data. But let's actually show a loading spinner if that is happening. So to show
a loading spinner, let's add a little article here. and built into Pico CSS. If you add Arya busy on an element, it'll actually show up as a little loading spinner. But I only want to show this if the status is pending. So we can do a V if here. We'll say if the status is equal to pending, show the loading spinner. Otherwise, render out the list.
And so I'm going to wrap this in a parent element. Add a v else here. And now if we are not loading, then please display the tasks. And now when we head to the app, we see a nice little loading spinner. It renders out the data. I can navigate around. When I head back, it makes that request on the client side and then the data gets loaded in. So this is nice and elegant. I like I said, working in other frameworks, it's not quite as easy to get that behavior of making it actually behave like a single page application when it's running on the client side. So this is pretty great. Now lastly, let's also show the error here because it's possible that our API endpoint will return an error.
sending api errors
So let's actually just immediately return. And there's a built-in helper called send error. We can pass in the event context which we get access to here in the event handler. And then there's another built-in called create error. And it has some nice defaults, but we can also pass in the status code. So let's say this is like a 500 status code. And we can pass in a custom status message. In this case, I'll just say, oh no, like something went wrong. So now when I hit this endpoint, it's going to take 2 seconds and then immediately return an error. But we have access to that error back on the homepage. So let's render it out here. So we will say if error has a value, then we would like to render out error.st status message.
Otherwise, if we're not pending and we don't have an error, list out all of the tasks. Now, I want this error message to show up with some red text. So I'm going to create my own class just called error. And then if I want some CSS to be globally available, I can just define that inside of my layout. Now, we are in a view component, so I could add a style tag here. But I know I'm going to have error classes throughout the app. So if we head to our layouts, if we add a style tag, any styles I define here will be accessible throughout the app. So let's just set the color to red. And now that error message should show up nice and red. So on the client side, it's spinning for two seconds. And then we get that error message. So that's awesome. Okay, let's get rid of the the fake error. Let's get rid of the wait and let's actually talk to a real database. So instead of just returning this list from memory, I'm going to go ahead and set up Drizzle to talk to a SQLite database. And then our endpoints can actually start listing from the database and and updating into the database. Now, I'm not going to walk you through how I do all of that because it's not nux, it's drizzle, but the longer course that I have coming out
soon on on full stack walks you through how to set all of that up. And the finished code for this video is also linked in the description. So, if you want to see how I set up the database, click that link and you can see all the files that I create. Okay, so my DB is all set up. You can see that now instead of returning a static list, I'm actually listing them from the database. They have the same format as that static list except now they have some timestamps.
db setup overview
And I went ahead and using Drizzle Studio, I inserted some sample data there. And now when we load the homepage, it's actually pulling those items from the database. Now, like I said, all this code is available link in the description, but a quick overview of what happened. I installed Drizzle and Lib SQL as dependencies. We have our drizzle config here which allows us to run drizzle kit and also create our migrations. In the lib folder, I've defined all of our DB stuffs. So the lib folder isn't a nux convention. I just put stuff in here that I'm going to manually import throughout my app. And in the DB folder, you can see I set up the connection to the database. And then our schema just has a single table, the tasks table. And we're also using Drizzle Zod to give us some validators for whenever we're inserting or updating into that specific table. Now, another thing I did was set up a type-S safe env. Now, Nux actually already has ready to go. And if you put anything in av file, you can actually directly access that throughout your app. You don't need to install anything extra. But I like to
see an error in the console if I'm ever forgetting any of these environment variables. So, I set up a validator with zod. And then in my Nux config, I import that env. So, when the next app starts up, if I'm missing any of those required environment variables, I'm immediately going to see an error. So, I also show you how to set this up in the more in-depth course that's coming soon. But for now, this pretty much has everything that we need. So, let's actually try creating a page that inserts tasks. So, if we go to the create task page, I want to have a form here that actually sends the data to my API to be inserted into the DB. So, if we head to the create page, let's create a parent element.
insert task
We'll have a form inside of here. I'll have a label. We'll be giving it the title of the task. We'll have an input. The name here is going to be title. And then we'll have a button which can submit the form. So we'll say create. Now I want that button to appear on the right. So I'm going to add a div. And we'll give this a class of button container. And then I'm going to define this class. And this similarly I want to be a global class. So in our layouts I'm going to specify the class here. And this is just going to be a flexbox. And we'll do justify content end. So it should push that button to the end and just like that I have a nice little form. So when I submit this form I want to actually send this data to my backend to insert into the DB. So let's create that endpoint. So here we'll create a new file. We'll call it tasks.post.ts. So when we receive a post request on API/tasks, this event handler is going to run. We'll define our event handler here and then we can get access to the event context. Now, whenever we're creating a task, we want to validate it
readValidatedBody
before putting it into the database. And built into H3, which we have access to because we're in NXT, is a method called read validated body. We can pass in the event and then we can pass in a function which will validate the body once it's actually been streamed in. And in this case, I just want to use the ZOD validator that I have from my schema.
So, in Drizzle, there is a package called Drizzle Zod. it can take a table definition and then give us back a validator. And you can see in this case, it's just going to make sure that that title exists and is a maximum of 500 characters. So I want to use this validator when I read in the validated body. So I'll pull in the insert task schema. And in this case, we're going to use safe parse because this will give us back the error. It won't throw an exception if there was an issue validating it. We will need to await this. And then I'm going to store this in a variable called result. Now if result.success success was not true, then that means there was some kind of validation error and we actually want to return that back to the client. So, we'll do the send error thing that I showed you a minute ago. Pass in the event, create our error. In this case, the status code is going to be a 422 unprocessable entity. And we'll also set up the message that just says invalid task like so. But if it was valid, let's just return what was sent to the API for
now before we put it into the database. So here I'm just going to say the task is result.data. Okay. So if we send a request here and it's not valid, this will throw an error. Let's call this endpoint from our component. So inside of here, I'll set up a script and essentially I want to send a request there when this form is submitted. So using view, we're going to tap into that submit event. We'll create a method called onsubmit. I'll prevent the default action and then our onsubmit function is going to do the work. Now, there's another built-in helper in Nux for making API requests and it's called dollar sign fetch and you typically want to use this one whenever you're making requests in response to some user event.
$fetch
So, in this case, when the user submits the form, we want to make a fetch. And this is fully type complete just like use fetch. But instead of being reactive and kind of just always listening at the top for if we navigate to this page or to load that data on server render, this is going to allow us to run this request on demand. So we're going to hit that endpoint and in this case we want to make a post request. So we'll set the method to post and our body for right now I'm going to send an empty body. So that way we'll actually get a validation error. Now dollar sign fetch is actually built on top of a library called oetch.
So it has a lot of nicities. You'll notice here that I don't have to stringify the body. I don't have to set the content type header. All of that's going to happen under the hood because of fetch. So let's give it a try. Let's make this an async method. We should get back the result and await it. And then for now, we'll just log out that result. And if there was any sort of error, let's log it out. So the other nice thing about fetch is if a fetch returns a non-successful status code, in this case, our endpoint is going to return a 422 because it's an invalid body. the catch will actually be run automatically. You don't have to look at like response. So for now, we'll just log out this error as well. Now, we also get full type completion here as well.
So you'll notice if I hover over result, you'll see that because I returned that object with task inside of it, it already knows what I'm going to be getting back here. But let's see this in action. So when I submit this form, I'm not sending any data at all. So we actually should see an error. Let's open up the dev tools. Clear it out. Submit.
Look at that. 422 invalid task. So all of this is nice and hooked up. Let's actually display this error if it happened. So I'm going to create some internal state in the component. We'll just have one called error message. And this will be a ref that starts off as the empty string. And then I also want to know if this is loading, right? Because it could take a second to create that task. So I'm going to create another state variable called loading.
And we'll default that to false. So now when I submit the form, we'll set loading to true. Reset the error message if there was one. And then when this is all said and done, we'll set loading to false. And now let's actually display that error message. So the type of error here is actually going to be a fetch error. That's a type that's built into fetch. So let me import that in. So we've got fetch error. And right here I can say let's grab the error. And this will be e as fetch error. And then we'll get some nice type completion. So here I can set error message dot value to be error dot. You'll see we get access to things like status code and status message. So I specifically want that status message. But this could be undefined because there could be some error that we didn't account for. So I can also give it a default message of like unknown error occurred. So now if there was an error, we can actually show it on the page. Let's just display it right above the form here. Make it an article and only show this if error message has a value. Display the error
message here. And we should also show a loading spinner. So we'll have this other article with Arya busy set to true and we'll show this by default if loading is true and then we can make an else here. So else if there's an error message show the error message. So if it's loading we'll show loading. If there's an error we'll show the error.
Otherwise if it's a success we can get that data back and then navigate the user to another page. So now let's actually send the data in this form. For this I'm just going to set up a state variable for that input. Let's call it task name. This will be a ref. starts off as the empty string and then we'll bind that to this input. So we can use vmodel and because that's bound whenever we submit the form we should have access to it. And here we can set the title to be task name dov valueue. But of course we don't want to allow the user to submit if that's empty. So let's just add an early return here. So if task name dovalue is not a thing. Let's also trim it just in case they put a bunch of spaces in there. But if that's the case then we will just set the error message.
So let's set error message.value value to be task is required and then we'll just do an early return. So now if I try submitting that's just a little bit of client side validation. Let's also add the error class on that so it shows up nice and red. So that looks good. But now I can actually send this to the API. So let's say learn nitro sends it to the API. We get back the response. Great.
Now let's actually put it into the database. So if we head to the post route right here is where I want to do the insert once it has been validated. So we'll do a nice little drizzle query. So this will insert into the test table the data that was validated and give us back the thing that got inserted. And this thing it gave us back will actually have an ID. So over on the other side once we get this data back we know the ID. So let's actually take the user to the page for that specific task. So in our pages I actually want a dynamic route. So we're going to have let's say tasks slash some id. So inside of here I can create a file called brackets id.view and this is how we can define parameters in the URL. So tasks slash one will load this page and get the task with ID 1 or task slash2 etc. So this is the page I want to go to once the task has been created. So for now let's just set up a quick little template. Give it
insert task
route params
a title the single task page. So that looks good. And then over on our create page right here once we get the data back, we can use navigate to. So this is built into next and lets us do programmatic navigation. This accepts that to object just like the nux link that I showed you earlier. So in this case, the name of the route we want to go to is tasks dash id. So you can essentially take the name of the path here, put dashes between it, and this will be the underlying name that Nux can recognize that route as. And then we can also pass in params. And in this case, we want to pass in the ID which will be result ID. This is the actual ID from the database. And so after successful creation, navigate to that page with that ID. Let's give it a try. So if we say learn Nitro, submit the form, it takes us to task three. If we look in Drizzle Studio, we have ourselves a new task. Fantastic. Now let's actually
display the task information on this page. So for that we'll need an API endpoint and our API endpoints can also have params. So I'll create a folder in here called tasks and in there I'll create a file which is ID brackets id.get.ts and this will retrieve a single task by ID. Now for this route, we actually want to validate the param in the URL, right? Because if they try to go to API/tasks/banana, we don't want to send banana to our lookup query because our database will complain that it's not a number because ID needs to be a number.
display single task
getValidatedRouterParam
So let's actually validate the incoming param. And just like they have read validated body, they also have get validated router params. And this works in the same way. We pass in the event and then we can pass in a validator. So I'm actually going to define a little ZOD schema right here called the ID params schema. We'll import Z from zod and then define a nice little object that's looking for that ID to be a number. So we can say coersse the incoming value as a number. And then I can use this schema right here. We'll use safe parse. Set it up in exactly the same way we did for our post route where read the result and then if it was not valid send back an error. In this case, we'll just say invalid ID. And I need to make sure that I await this. So that looks great. So when they make a request here, make sure that there is a valid ID. If it was a valid ID, let's actually look it up in the database. So we'll use that ID that we got from validating the params to look it up. And then if the
find first task with id
task was not found, so if this is undefined, we actually want to return a 404 error. So we can do a similar send error, set this up as a 404, and just say task not found. But if the task was found, we will return it. So now on our task page, let's actually request this endpoint. And this is another scenario where I want to use use fetch because anytime I go to this page, it should request from that endpoint and load in the latest data for this task. So it's going to be very similar to what we did on our index page, but in this case, it's going to be for a single task. So let's create our script. But in this case, we want to make the request to API/tasks slash some id. And the way we can get that ID inside of a page is by using the current route. So built into nux is this composable called use route.
useRoute
This gives you all the information about the current route including the params. So if I say route.params ID, that'll give me the ID param when they're on this specific page. We'll make the get request here. We want it to be lazy. And this is going to give us back a single task. Now, just like before, I'll show some loading state. I'll show the error. So, I'm going to copy that from the index page.
list single task
And then, if we're not loading and there was no error, we'll render out for now just the task title. And we can also use a v else here. So, v else if task actually exists, then we don't have to use optional chaining. So, now when I head to task/3, it gives me back that one specific task. We head back to the homepage. Let's add some links here. So we can go to the task page for each of these. So back on the homepage, let's add the button container here. We'll have a next link that just says view.
And in this case, we want to go to that specific task. So we can bind to the two prop pass in our options. We want to go to the page that is called tasks- ID. And our params in this case, the ID will be task ID. And then lastly, if I give this nux link a ro of button, pico CSS will style it as a as a button. So now we have this nice little view button. I can click here that loads the task with that ID. I can click here, loads the task with that ID, etc. Now I do want to see these loading spinners because it's just so fast. I want to make sure that all of that is working and it should because we tested it on the homepage.
We're doing it in a very similar way. But in this specific endpoint, let's actually wait a second before returning the data. So, we'll wait one second, then do all of our validation and lookup and everything else. And now when I go to the page, it's loading and then we get the data. It's loading. We get the data, but our errors should come through as well. So, if I pass in an ID that does not exist, we should get back that error from the API that says task not found. And if I pass banana as the ID, we should get back that error that says invalid ID as well. Awesome. So, here's our nice little app. We can view tasks.
We can create tasks. I'm actually going to end the tutorial here because I'm going to leave it as an exercise to you if you want to update tasks. So, what I think you should do is have this page here actually have a form where we can change the title of the task. We can mark it as done or not done and we can also delete tasks. So, I have shown you everything and given you all the all the tools you would need to do that.
homework
Essentially, we'll need an endpoint for updating. We'll need an endpoint for deleting. Inside the single task page, we can create a form for updating. So, everything I showed you here is enough for you to to get all of that working. Now, I have just scratched the surface of what's possible with Nux, but hopefully this gets you up and going and building some Nux apps. Like I said, pretty soon on the channel, I will be releasing an in-depth full stack tutorial where we build an app with multiple pages and nested routes and a whole a whole lot more. Um, but I would say for now, spin up a NXT app, give it a try. Um, and I'll also say that there are other ways to build apps as well, right? But what I showed you here is more of a a full stack application where we're creating API endpoints, requesting data. Next also supports the ability of kind of just working with content. So if you look in the directory structure, there is this folder called content. And this allows you to build out server rendered apps that just have pages that use markdown or other content types. And then there are actually ways of loading that content in. So, this is another way
thanks!
you might build a Nux app. Maybe you're not talking to a database. Maybe it's like a CMS with like blog post or something like that. That's definitely a way you could use Nux as well. We really just scratched the surface. Like I said, stay tuned for the more in-depth tutorial. But if you enjoyed this, let me know down in the comments. If you have any questions, let me know as well. And I'll see you in the next one.
Quote it with credit and a link. Quoting Syntax