Nuxt Tip: Adding a Latest Route
Utilizing Nuxt Middleware you can implement an easy way for visitors to always read the latest blog posts (or any other content) without needing to know its name or specific URL.
Let's take a look at the route middleware's code:
Route middleware are navigation guards that receive the current route and the next route as arguments. First, you need to check if the fullPath
of the current route equals the expected latest route.
Next, we use Nuxt Content's queryContent function to find the latest blog post using the sort({ date: -1 })
query.
Finally, we use the navigateTo
function, which is globally available in Nuxt and redirects to the given route.
Info
Want to give it a try? Try navigating to https://mokkapps.de/blog/latest!
If you liked this Vue tip, follow me on X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:
Vue Tip: Typing Component Events
To declare emits with full type inference support, we can use the defineEmits API, which is automatically available inside <script setup>.
Pinia Tip: Use Setup Stores for More Flexibility
Besides Option Stores you can also use Setup Stores to define stores in Pinia. They bring more flexibility as you can create watchers within a store and freely use any composable.