2

I have an universal NodeJS, Express, React/Redux app that uses react-router. It is rendered from server side on initial requests of the app and on client on subsequent requests that come from react-router.

My routes.js file:

<Route path="/" component={App}>
    <Route path="/main" component={Main}/>
    <Route path="/login" component={Login}/>
</Route>

I have a wildcard express route that matches this react-routes and sends the component markup back to the template:

import routes from '../routes';

app.get('*', (req, res) => {
    match(
        { routes, location: req.url },
        (err, redirectLocation, renderProps) => {
            let markup;
            if (renderProps) {
                markup = renderToString(
                    <Provider store={store}>
                        <RouterContext {...renderProps}/>
                    </Provider>
                );
            } else {
                markup = renderToString(<NotFoundPage/>);
                res.status(404);
            }

            return res.render('index', { markup });
        }
    );
});

Now I want to protect some of the routes intercepted by the wildcard route using passport-jwt, like the example:

app.get("*", passport.authenticate('jwt', { session: false }), 
(req, res) => {
    match(
        { routes, location: req.url },
            (err, redirectLocation, renderProps) => {
                res.json("Success! You can not see this without a token");
            }
    )
});

How can I protect only a given route from routes.js on wildcard route?

1 Answer 1

1

you can add some middleware to do this via app.use. (https://expressjs.com/en/4x/api.html#app.use)

just be sure to call this before your wildcard handler

app.use("/main", passport.authenticate('jwt', { session: false }), 
function(req, res){
    res.json("Success! You can not see this without a token");
});
Sign up to request clarification or add additional context in comments.

3 Comments

Actually I want to make selective protection on my wildcard routes while server side rendering. Do you know how can I use middleware on this case?
Let's assume (just an example) you want to protect anything behind /admin with your token authentication middleware. To do so you would utilize app.use('admin', passport.authenticate('jwt', { session: false }) before you declare your wildcard handler. Middleware functions are executed sequentially, therefore the order of middleware inclusion is important.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.