Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
"url": "https://github.com/pablopunk/nextjs-redirect"
},
"scripts": {
"build": "sucrase src -d dist --transforms imports,typescript && npm run generate-types && npm run prettier",
"build": "sucrase src -d dist --transforms imports,typescript,jsx && npm run generate-types && npm run prettier",
"generate-types": "dts-bundle-generator -o typings.d.ts src/index.tsx",
"prettier": "prettier src/*.tsx ./typings.d.ts --write",
"prepare": "npm run build"
Expand Down
47 changes: 38 additions & 9 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,26 +1,55 @@
import React from 'react'
import Router from 'next/router'
import Head from 'next/head'

export default (
redirectUrl: string,
options?: { asUrl?: string; statusCode?: number }
) =>
class extends React.Component {
// Redirects on the server side first if possible
static async getInitialProps({ res }) {
if (res) {
if (res?.writeHead) {
res.writeHead(options?.statusCode ?? 301, { Location: redirectUrl })
res.end()
} else {
if (options?.asUrl != null) {
Router.push(redirectUrl, options.asUrl, { shallow: true })
} else {
Router.push(redirectUrl)
}
}

return {}
}

// Redirects on the client with JavaScript if no server
componentDidMount() {
if (options?.asUrl != null) {
Router.push(redirectUrl, options.asUrl, { shallow: true })
} else if (redirectUrl[0] === '/') {
Router.push(redirectUrl)
} else {
window.location.href = redirectUrl
}
}

render() {
return React.createElement('div')
const href = options?.asUrl ?? redirectUrl
return (
<>
<Head
children={
<>
{/* Redirects with meta refresh if no JavaScript support */}
<noscript>
<meta httpEquiv="refresh" content={`0;url=${href}`} />
</noscript>
{(options?.statusCode === undefined ||
options?.statusCode === 301) && (
<link rel="canonical" href={href} />
)}
</>
}
/>
{/* Provides a redirect link if no meta refresh support */}
<p>
Redirecting to <a href={href}>{href}</a>&hellip;
</p>
</>
)
}
}
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
{
"compilerOptions": {
"jsx": "react",
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"skipLibCheck": true,
Expand Down
1 change: 1 addition & 0 deletions typings.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ declare const _default: (
}
) => {
new (): {
componentDidMount(): void
render(): any
}
getInitialProps({ res }: { res: any }): Promise<{}>
Expand Down