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.jsÂmodule .exports = {asyncrewrites () {return [{source : '/@:slug',destination : '/artists/:slug',},]},}
js
// next.config.jsÂmodule .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 hereÂreturnunparsedPath }Â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 hereÂreturnunparsedPath }Âconstlinking :LinkingOptions <ReactNavigation .RootParamList > = {// ...your linking configprefixes : [Linking .createURL ('/'), 'https://fernandorojo.co'],getStateFromPath (path ,config ) {constfinalPath =withRewrites (path )ÂreturngetStateFromPath (finalPath ,config )},}