errors/no-location-assign-relative-destination.mdx
Prevent usage of
location.assign()orlocation.hrefassignment to navigate to internal Next.js pages.
location.assign() or location.href = ... was used to navigate to a relative URL. In Next.js, this bypasses the client-side router, causing a full page reload and losing any prefetched data or state managed by the framework.
Use redirect() from next/navigation:
import { redirect } from 'next/navigation'
export default function Page() {
redirect('/dashboard')
}
'use client'
import { redirect } from 'next/navigation'
export default function MyComponent({
isAuthorized,
}: {
isAuthorized: boolean
}) {
if (!isAuthorized) {
redirect('/login')
}
return <div>Protected content</div>
}
Use useRouter().push() from next/navigation:
'use client'
import { useRouter } from 'next/navigation'
export default function MyButton() {
const router = useRouter()
return (
<button onClick={() => router.push('/dashboard')}>Go to Dashboard</button>
)
}
If you are navigating to an external URL (one with a protocol, e.g. https://), location.assign() and location.href are acceptable and will not trigger this rule:
// Allowed — navigating to an external site
location.href = 'https://example.com'
window.location.assign(`https://example.org/${path}`)
// Allowed — variable with absolute URL prefix
const url = 'https://example.com/' + path
location.href = url
If the rule cannot statically determine whether a value is absolute or relative (e.g., function calls, event properties), the check is skipped:
// Skipped — cannot determine statically
const url = getUrl() // Function call
location.href = url
// Skipped — cannot determine statically
location.href = event.target.href