fridays / next-routes

Universal dynamic routes for Next.js
MIT License
2.47k stars 230 forks source link

Redirecting to dynamic route with modified query param #41

Closed sedubois closed 7 years ago

sedubois commented 7 years ago

Hi and thanks again for this library, it's really helpful!

I have a case where I need to redirect when the user enters a URL which doesn't contain the locale. E.g if they go to "/", I want to redirect to "/en". If they go to "/courses", I want to redirect to "/en/courses". I have set up all the dynamic routes accordingly, seems to work. But I don't know how to redirect using the asPath instead of the hidden URL (e.g how to redirect to "/en" instead of "/?locale=en"). Any hints?

My code currently looks like this:

import { format } from 'url'

...
  static async getInitialProps(ctx) {
    if (!process.browser) {
      if (!ctx.query.locale) {
        const sessionLocale = ctx.req.session ? ctx.req.session.user.locale : 'en'
        const { pathname, query } = ctx
        query.locale = locale = sessionLocale
        ctx.res.writeHead(302, { Location: format({ pathname, query }) });
        ctx.res.end();
      }
      ...
    }
    ...
  }

Thanks a lot

HaNdTriX commented 7 years ago

next-routes has some handy methods to get the current route. Right now they are not documented so use them with care:

import router from '../routes'
import { parse } from 'url'

...
const { pathname, query } = parse(req.url, true)
const { route } = router.match(pathname)
route.getAs(query)
...

or

import router from '../routes'

const route = router.findByName(<routeName>)
route.getAs(query) 

Please let me know if this hint helps.

sedubois commented 7 years ago

Thanks @HaNdTriX, I had a look but didn't get it working that way. But actually I can normally simply do this with plain next.js:

import Router from 'next/router'
...
const { pathname, query, asPath } = ctx
return `/${query.locale}${asPath}`