|
1 | 1 | import React from 'react'
|
2 | 2 | import Router from 'next/router'
|
| 3 | +import Head from 'next/head' |
3 | 4 |
|
4 | 5 | export default (
|
5 | 6 | redirectUrl: string,
|
6 | 7 | options?: { asUrl?: string; statusCode?: number }
|
7 | 8 | ) =>
|
8 | 9 | class extends React.Component {
|
| 10 | + // Redirects on the server side first if possible |
9 | 11 | static async getInitialProps({ res }) {
|
10 |
| - if (res) { |
| 12 | + if (res?.writeHead) { |
11 | 13 | res.writeHead(options?.statusCode ?? 301, { Location: redirectUrl })
|
12 | 14 | res.end()
|
13 |
| - } else { |
14 |
| - if (options?.asUrl != null) { |
15 |
| - Router.push(redirectUrl, options.asUrl, { shallow: true }) |
16 |
| - } else { |
17 |
| - Router.push(redirectUrl) |
18 |
| - } |
19 | 15 | }
|
20 |
| - |
21 | 16 | return {}
|
22 | 17 | }
|
| 18 | + |
| 19 | + // Redirects on the client with JavaScript if no server |
| 20 | + componentDidMount() { |
| 21 | + if (options?.asUrl != null) { |
| 22 | + Router.push(redirectUrl, options.asUrl, { shallow: true }) |
| 23 | + } else if (redirectUrl[0] === '/') { |
| 24 | + Router.push(redirectUrl) |
| 25 | + } else { |
| 26 | + window.location.href = redirectUrl |
| 27 | + } |
| 28 | + } |
| 29 | + |
23 | 30 | render() {
|
24 |
| - return React.createElement('div') |
| 31 | + const href = options?.asUrl ?? redirectUrl |
| 32 | + return ( |
| 33 | + <> |
| 34 | + <Head |
| 35 | + children={ |
| 36 | + <> |
| 37 | + {/* Redirects with meta refresh if no JavaScript support */} |
| 38 | + <noscript> |
| 39 | + <meta httpEquiv="refresh" content={`0;url=${href}`} /> |
| 40 | + </noscript> |
| 41 | + {(options?.statusCode === undefined || |
| 42 | + options?.statusCode === 301) && ( |
| 43 | + <link rel="canonical" href={href} /> |
| 44 | + )} |
| 45 | + </> |
| 46 | + } |
| 47 | + /> |
| 48 | + {/* Provides a redirect link if no meta refresh support */} |
| 49 | + <p> |
| 50 | + Redirecting to <a href={href}>{href}</a>… |
| 51 | + </p> |
| 52 | + </> |
| 53 | + ) |
25 | 54 | }
|
26 | 55 | }
|
0 commit comments