Javascript is required
Mokkapps LogoMichael Hoffmann

Nuxt Tip: Adding a Latest Route

Michael Hoffmann (Mokkapps) - Senior Frontend Developer (Freelancer)
Michael Hoffmann
Jan 11, 2023
1 min read
Nuxt Tip: Adding a Latest Route Image

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:

export default defineNuxtRouteMiddleware(async (to, from) => {  if (to.fullPath === '/blog/latest') {    const data = await queryContent('blog').where({ _partial: false }).sort({ date: -1 }).findOne()    navigateTo(data._path)  }})

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.


Want to give it a try? Try navigating to!

If you liked this Vue tip, follow me on Twitter to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue newsletter.