The Better Nuxt Directus Authentication Middleware

 Sep 26, 2023 ·  Nov 11, 2023 ·  2min read

Technology Tutorials

The Nuxt Directus docs give you a basic auth middleware, but it’s got some quirks. Here’s how to bulletproof it. [Edited Nov 11, 2023]


Why Nuxt and Directus are a Match Made in Dev Heaven 

Starting an app from scratch is like reinventing the wheel—unnecessary and time-consuming. That’s why we have killer frameworks like Nuxt (“The Intuitive Web Framework”) for frontend magic and Directus (“The backend to build anything or everything”) for backend wizardry. I’m currently using both to build PrioMind.

Edited Nov 11, 2023 

In the meantime, I’ve switched to Supabase as backend for PrioMind. Supabase also comes with “batteries included”—i.e., authentication. When using the Nuxt Supabase module, the middleware comes built-in.

But here’s the kicker: There’s a package named Nuxt Directus that marries these two like peanut butter and jelly. Sweet, right?

The Good, the Bad, and the Ugly of Nuxt Directus 

Nuxt Directus is a lifesaver, no doubt. It lets you pull and push data from your Directus backend to your Nuxt frontend like a pro. User signup, login, you name it—it’s got you covered.

But let’s keep it real: the docs are kinda basic. They offer an example middleware to redirect unauthenticated users to a login page, which is crucial for any app with restricted access. Problem is, this middleware has a nasty habit of logging you out when you least expect it.

The Middleware You’ve Been Waiting For 

Enough talk. Here’s a middleware that’s not just a band-aid but a full-on cure. It’ll protect your routes and keep your login sessions intact:

// ~/middleware/auth.ts
export default defineNuxtRouteMiddleware(async (to, _from) => {
  const { token_expired, checkAutoRefresh } = useDirectusToken()

  // Check if the token's expired
  if (token_expired.value) {
    try {
      // Attempt to refresh the token
      await checkAutoRefresh()
      // If still expired, off to the login page
      if (token_expired.value) {
        return navigateTo('/login')
      }
    } catch (error) {
      // Handle any refresh errors here
      console.error("Couldn't refresh token:", error)
    }
  }
  // If the token's good, carry on
})

To use this gem, slap it onto any Nuxt page that needs authentication:

<script setup lang="ts">
definePageMeta({
  middleware: ['auth']
})
</script>

That’s it, you’re good to go.

Summary 

So, there you have it—a rock-solid fix for the authentication middleware in Nuxt Directus. The out-of-the-box example might leave you scratching your head with random logouts, but this solution is your ticket to a hassle-free user experience. Implement this, and you can focus on building out the cool parts of your app without worrying about unexpected session timeouts.

About the Author

Michael Schmidle

Founder of PrioMind. Start-up consultant, hobby music producer and blogger. Opinionated about technology, strategy, and leadership. In love with Mexico. This blog reflects my personal views.

 LinkedIn  GitHub  SoundCloud

Recommended Articles

 Jul 11, 2024 ·  3min read

Integrating Termly With Nuxt 3

Integrating Termly’s consent management with Nuxt 3 turns out to be harder than just inserting a script tag. Here’s a solution that resolves hydration mismatches and UI glitches, ensuring smooth functionality and user experience. Continue…

Technology Tutorials


 Nov 15, 2023 ·  2min read

Mastering Keyboard Interactions in Shadcn-Vue: A Fix for Complex UIs

In the intricate dance of UI components within Vue applications, a misstep can disrupt the rhythm. Discover how a straightforward tweak can harmonize your keyboard interactions in shadcn-vue in complex nested components. Continue…

Technology Tutorials


 Apr 18, 2020 ·  6min read

Accelerate Your Website—With Your Logo

Most people who care about their website’s performance probably use a website logo created by vector graphics software. Here’s how to take advantage of vectorized logos to speed up your website. Seriously. Continue…

Technology Tutorials


 Aug 18, 2019 ·  May 14, 2020 ·  6min read

Unhide Virtual Network Adapters in Windows 10

In Windows’ latest releases, Microsoft hides virtual adapters and networks by default. In some cases though, you need them to be available just like regular adapters and networks. Continue…

Technology Tutorials