Redirect to multiple routes based on JWT Claim using vuejs routes - vuejs3

Currently i have the following route
routes.push({
path: "/",
redirect: "/Dashboard"
});
When I login, it will redirect me to the /dashboard screen.
But how can I update the route so that when I log in I can check the claims and then based on the role, redirect to a different view.
I tried the following, this is just sudo code as I cant really get it to work. Also if I can I would like to add an alias. Even if I can get it to work is would this be the correct way of doing it?
routes.push({
path: "/",
alias: "/dashboard", --> This does not seem to work with redirect.
redirect: to => {
getUserType(msalInstance).then(userType => {
if(userType == 'Client'){
return { path: '/clients/2/detail' }
}
else {
return { path: '/dashboard' }
}
});
}
});
and the route for the client-detail looks as follows.
routes.push({
path: "/clients/:id?/detail",
name: "client-detail",
props: true,
meta: {
requiresAuth: true,
layout: simpleLayout,
allowedUsers: clientUserTypes
},
component: loadView("client-detail"),
});
I have looked the the beforeEnter hook but when I add it, it seems to get ignored because the redirect is there.

Related

Next.js Redirects: redirects key in next.config.js vs. redirect object in getServerSideProps()

Let's just say I want to redirect my index page to the about page in Next.js. It seems like I have 2 options:
1. Adding the redirects key in next.config.js
module.exports = {
async redirects() {
return [
{
source: '/',
destination: '/about',
permanent: true,
},
]
},
}
2. Returning the redirect object inside the getServerSideProps() function
// pages/index.js
export async function getServerSideProps() {
return {
redirect: {
destination: '/about',
permanent: true,
},
};
};
What is the difference between these 2 options?
According to your logic, they're the same in terms of functionality, but redirect on your page pages/index.js will have more flexibility and more customization. For example, you want to redirect to another page conditionally like below
// pages/index.js
export async function getServerSideProps() {
const value = true; //receive data from APIs
//if value is true, redirect to `/help` instead of `/about`
if(value) {
return {
redirect: {
destination: '/help',
permanent: true,
},
};
}
//TODO: You can add your logic here before redirection
return {
redirect: {
destination: '/about',
permanent: true,
},
};
};
You cannot achieve that logic with redirects() under next.config.js. You can imagine that it's like configurations being only applied once without the complicated logic requirement.
You can consider these use cases:
If you don't want to have complicated routing logic and just use them as one-time setups - Use redirects() in next.config.js
If you have some logic to handle routings in pages and it's relied on external resources - Use redirect in pages themselves

How to rewrite homepage based on hostname

I'd like to show two different pages at '/' depending on the hostname (the value for req.hostname). This is because I have a subdomain xxx.mydomain.com that needs to show just one page at the root URL. The idea is to have a CNAME for the subdomain that points to the same server as www. I'm using next version 11.1.2 .
My homepage (/pages/index.js) uses getStaticProps to get data for the page with a revalidate interval of 2 seconds. The page on the production branch works great currently without any rewriting.
I tried using the rewrites option in next.config.js and was able to use this to rewrite all other routes, but rewriting with source: '/' did not do anything. If the source was any other page it worked perfectly. This is pretty much what the next.config.js file looked liken when I tried the rewrite:
const withFonts = require('next-fonts');
const withTM = require('next-transpile-modules')(['#cal-frontends/shared']);
require('dotenv').config({ path: '../../.env' });
module.exports = withTM(withFonts({
async rewrites() {
return [
{
source: '/', // this one still showed the homepage at '/'
destination: '/mission',
},
{
source: '/foo', // this one showed the contact page at '/foo'
destination: '/contact',
},
]
},
webpack(config, options) {
return config;
},
}));
I tried many strategies, including this kind of configuration in server.js
server.get('/',function(req,res){
console.log('trying to redirect', )
console.log('req.hostname', req.hostname)
if (req.hostname === 'mission.mydomain.com') {
console.log('this should show mission', )
return app.render(req, res, '/mission', {})
} else {
handle(req, res);
}
});
This unfortunately did not seem to override the static caching that happens with getStaticProps – you will only see the correct page for the hostname if you load and then reload after it revalidates.
Is there an elegant way to do this?

Next.js redirect www to non www

I have been trying to find a workable solution this searching google but can't find anything solid. I am hosting my Next.js application on Vercel.
When I run a seo check it moans about me having the site available on www and non www and says I should pick one and get it to redirect so in my case, if someone types in www.example.com I would prefer it left of the www.
Since I don't have a htaccess file I can do this in, how would I do it?
Not sure if it matters, but I am using WordPress as my backend aka: Headless Wordpress
You should be able to use host-based redirects now since Next v10.2. See https://nextjs.org/docs/api-reference/next.config.js/redirects#header-cookie-and-query-matching.
In next.config.js:
module.exports = {
// ...
redirects: async () => [
{
source: '/:path*',
has: [{ type: 'host', value: 'www.yourdomain.com' }],
destination: 'https://yourdomain.com/:path*',
permanent: true
}
]
}
you can easily handle permanent redirection in nextjs using the below-mentioned code.
export const getServerSideProps = async (context) => {
const { req, res } = context;
if (req.headers.host.match(/^www/) !== null) {
res.writeHead(301, {
location: "https://" + req.headers.host.replace(/^www./, "") + req.url,
});
res.end();
}
return { props: {} };
};

Flowrouter - have to reload whole page for route to be recognised

Quite basic setup - user submits a post, it's inserted by a method, then user should be routed to a confirm page with the _id of the newly created post:
const onSubmitPost = (post) => {
createPost.call(post, (err, res) => {
if(err) {
instance.errorMessage.set(err.reason);
} else {
FlowRouter.go("create-post/:postId/confirm", { postId: res });
}
});
};
// Route definition
FlowRouter.route("/create-post/:postId/confirm", {
name: "create-confirm",
action() {
BlazeLayout.render("MainPage", { content: "ConfirmPostContainer" });
}
});
But when I try this, I get There is no route for the path: create-post/abc123/confirm
If I manually press reload, it works fine - no problems.
Anyone have any idea what's going on, and how to fix?
EDITS
This is called on the /create-post route - redirect to confirm the
post after it's created
Added route definition
Tried using redirect instead of go - no difference
There are 2 things I can suggest you to try. My hunch is that the problem stems from calling the .go method from /create-post with a relative path.
So, first, try route-names instead: FlowRouter.go('create-confirm', { postId: res });
Second, try absolute paths: FlowRouter.go('/create-post/' + res + '/confirm'); - notice the leading slash / !
Does that work?
try FlowRouter.redirect(YOUR ROUTE NAME , { postId: res }

FlowRouter redirect if user is logged in and if path is

I'm using Meteor with FlowRouter and i'm looking for a condition like this:
if the user is logged && if the accessed path is http://x.x.x.x/
then redirect to http://x.x.x.x/clients
My current Routes:
Accounts.onLogin(function(){
FlowRouter.go('clients');
});
Accounts.onLogout(function(){
FlowRouter.go('home')
});
FlowRouter.triggers.enter([function(context, redirect){
if(!Meteor.userId()){
FlowRouter.go('home')
}
}]);
FlowRouter.route('/', {
name: 'home',
action(){
BlazeLayout.render('HomeLayout');
}
});
FlowRouter.route('/clients',{
name: 'clients',
action(){
BlazeLayout.render('MainLayout', {main: 'Clients'});
}
});
if(Meteor.userId() && FlowRouter.getRouteName() === 'route_name'){
FlowRouter.go('/route_name');
}
In flow router docs there are a few was to get the current route if you need to restructure the statement above.
https://github.com/kadirahq/flow-router/blob/master/README.md
I'd say that you just have to change your FlowRouter.route('/'...) configuration a bit:
FlowRouter.route('/', {
triggersEnter: [function(context, redirect) {
if (Meteor.userId()) {
redirect('/clients');
}
}],
name: 'home',
action(){
BlazeLayout.render('HomeLayout');
}
});
So any logged in user that accesses '/' will be redirected to 'clients' - worked fine when I tested it. Here's some background info in the flow router docs: https://github.com/kadirahq/flow-router/blob/master/README.md#redirecting-with-triggers

Resources