Javascript is required
1 min read

Nuxt Tip: Adding a Latest Route

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:

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

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 X to get notified about new tips, blog posts, and more. Alternatively (or additionally), you can subscribe to my weekly Vue & Nuxt newsletter:

I will never share any of your personal data. You can unsubscribe at any time.