Set default value for a dynamic route/ page in Nuxt.js?

Viewed 616

When someone is referred to my site I want the URL to look something like this

localhost:3000/<dynamic affiliate username>/home

But when someone is not referred to my site and is a guest I would like the URL to default to something like this

localhost:3000/www/home

Is there a way for me to set a default value for a dynamic route/ page using Nuxt.js?

1 Answers

Use middleware

1. Page middleware

You can check the user in middleware (by cookie or something else you use. In this example I used nuxt auth module)

Named middleware
/* pages/_user/home.vue */
export default {
  middleware: "auth"
}
Anonymous
/* pages/_user/home.vue */
export default {
  middleware({ $auth, redirect }) {
    if(!$auth.loggedIn) {
      redirect("/www/home")
    }
  }
}

2. Router middleware

If you want to apply this logic globally in the project (on each child route of _user page for example), you can set router middleware in nuxt.config.js

/* nuxt.config.js */
export default {
  router: {
    middleware: ["auth"] // or "auth" for single middleware 
  }
}
/* middleware/auth.js */
export default ({ $auth, route, redirect }) => {
  if(funcToDetectUserPage(route.path)) {
    if(!$auth.loggedIn) {
      redirect("/www/home");
    }
  }
}
Related