Redirects
Imagine you want users to enter the URL /@drake
, and for it to redirect to the page at /artists/[slug].tsx
.
Next.js lets you handle this easily with redirects and rewrites inside of next.config.js
js
// next.config.jsmodule .exports = {asyncrewrites () {return [{source : '/@:slug',destination : '/artists/:slug',},]},}
js
// next.config.jsmodule .exports = {asyncrewrites () {return [{source : '/@:slug',destination : '/artists/:slug',},]},}
The issue is, this won't work out of the box with React Navigation.
In order to achieve the same, we'll need to edit the React Navigation linking config.
tsx
import * asLinking from 'expo-linking'import {getStateFromPath ,LinkingOptions } from '@react-navigation/native'constwithRewrites = (unparsedPath : string): string => {if (unparsedPath .startsWith ('/@')) {constslug =unparsedPath .replace ('/@', '').split ('?')[0].split ('/')[0]constrest =unparsedPath .replace (`/@${slug }`, '')return `/artists/${slug }${rest }`}// you can put other redirects herereturnunparsedPath }constlinking :LinkingOptions <ReactNavigation .RootParamList > = {// ...your linking configprefixes : [Linking .createURL ('/'), 'https://fernandorojo.co'],getStateFromPath (path ,config ) {constfinalPath =withRewrites (path )returngetStateFromPath (finalPath ,config )},}
tsx
import * asLinking from 'expo-linking'import {getStateFromPath ,LinkingOptions } from '@react-navigation/native'constwithRewrites = (unparsedPath : string): string => {if (unparsedPath .startsWith ('/@')) {constslug =unparsedPath .replace ('/@', '').split ('?')[0].split ('/')[0]constrest =unparsedPath .replace (`/@${slug }`, '')return `/artists/${slug }${rest }`}// you can put other redirects herereturnunparsedPath }constlinking :LinkingOptions <ReactNavigation .RootParamList > = {// ...your linking configprefixes : [Linking .createURL ('/'), 'https://fernandorojo.co'],getStateFromPath (path ,config ) {constfinalPath =withRewrites (path )returngetStateFromPath (finalPath ,config )},}