Comments (10)
Admin route + redirect example:
client.js
import UniversalRouter from 'universal-router'
import { createHistory } from 'history'
import routes from './routes'
history = useQueries(createBrowserHistory())
history.listen(onLocationChange)
history.replace(history.getCurrentLocation()); // initial render
async function onLocationChange(location) {
try {
const routeActionResult = await UniversalRouter.resolve(routes, {
path: location.pathname,
store: { isAdmin: false },
redirect(to) {
const error = new Error(`Redirecting to "${to}"...`)
error.status = 301
error.path = to
throw error
}
})
syncOrAsyncClientSideRenderFn(routeActionResult)
} catch (error) {
if (error.status === 301) {
history.replace(error.path || '')
return
}
// log or display other errors here
}
}
server.js
import express from 'express'
import UniversalRouter from 'universal-router'
import routes from './routes'
const server = express()
const port = process.env.PORT || 3000
app.get('*', async (req, res, next) => {
try {
const routeActionResult = await UniversalRouter.resolve(routes, {
path: req.path,
store: { isAdmin: false },
redirect(to) {
const error = new Error(`Redirecting to "${to}"...`)
error.status = 301
error.path = to
throw error
}
})
const html = syncOrAsyncServerSideRenderFn(routeActionResult)
res.status(200).send(html)
} catch(error) {
if (error.status === 301) {
req.redirect(status.path || '/')
return
}
next(error)
}
})
server.listen(port, () => {
console.log(`Node.js app is running at http://localhost:${port}/`)
})
routes.js
export default [
{
path: '/',
action() {
return 'main page'
}
},
{
path: '/login',
action() {
return 'login page'
}
},
{
path: '/admin',
action({ store, redirect }) {
if (store.isAdmin) return 'admin page'
return redirect('/login') // or return undefined to render 404 instead
}
}
]
from universal-router.
This is roughly what I have. I'm not satisfied but it works for now.
router.js
const authorize = (state, next) => {
if (!state.isAuthenticated) {
state.redirect = '/login'; next();
}
}
// If trying to access login page when Authenticated
const redirectAuth = (state, next) => {
if (state.isAuthenticated) {
state.redirect = '/';
}
}
const router = new Router(on => {
on('*', async (state, next) => {
const component = await next();
return component && <App context={state.context}>{component}</App>;
});
// Authenticated pages
on('/editor', async (state, next) => {
authorize(state, next);
return (
<EditorPage />
)
});
// Public pages
on('/login', async (state, next) => {
redirectAuth(state, next);
return (
<LoginPage />
)
});
})
app.js
function run() {
let currentLocation = null;
let currentState = null;
// Make taps on links and buttons work fast on mobiles
//FastClick.attach(document.body);
ReactTapEvent();
// Check cookies if already logged in
AppActions.isLoggedIn();
let isAuthenticated = AppStore.isAuthenticated();
// Get user data if authenticated
if (isAuthenticated) {
let userId = AppStore.getAuth().userId;
AppActions.getUser(userId);
}
// Re-render the app when window.location changes
const unlisten = Location.listen(location => {
isAuthenticated = AppStore.isAuthenticated();
currentLocation = location;
currentState = Object.assign({}, location.state, {
path: location.pathname,
query: location.query,
state: location.state,
isAuthenticated: isAuthenticated,
context
});
render(currentState);
});
...
from universal-router.
@langpavel nope, it is just the easiest way to stop executing all routing code. In other way you need to handle redirect in several places (for example in each root/parent route) or add implementation to the core of router. But I do not see anything wrong with the exception approach, because we still need to handle errors such as 404 or 500.
from universal-router.
@rstormsf can you give me full example?
from universal-router.
A redirect example would be useful.
from universal-router.
@mfrye what is ReactTapEvent() ?
from universal-router.
@koistya is there any possibility now to redirect to different route? I see that post is quite old and universal-router API has changed since then?
from universal-router.
@frenzzy would be great to see such example in documentation :)
from universal-router.
@frenzzy It is needed do redirect through exception?
from universal-router.
@frenzzy It seems that there is already a try catch block for route action in resolve function which take precedence over the try catch block above. For now, I set a boolean for redirection when required and use that to redirect later.
from universal-router.
Related Issues (20)
- bad documentation in 'Getting Started' page HOT 1
- How does universal router handle conflicts? HOT 1
- Question: Routing based on backend logic HOT 3
- Synchronous operation HOT 3
- Recipe for GraphQL state management vs. Redux would be great HOT 1
- middleware TypeError for not found routes HOT 1
- Getting child route's params in middleware HOT 2
- generateUrls() does not work with universal-router/sync HOT 2
- Update Hyperapp url in README
- BUG: route dose not resolve ? HOT 2
- overriding Route type when initializing UniversalRouter HOT 5
- update path-to-router dependency to latest HOT 1
- TypeScript 3.8.3: type checking failing HOT 9
- Incorrect TypeScript RouteParams Interface HOT 2
- Middlware approach context.next and redirection HOT 2
- Bug: Empty children array shouldnt be required when dynamically defining routes HOT 2
- Nested url generation HOT 2
- Simple Change: Make resolveRoute a class member of UniversalRouter instead of privately scoped HOT 1
- how to handle "not found (404)" page? HOT 1
- Redirects?? HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from universal-router.