Back to Next Js

No location.assign or location.href navigation to relative URLs

errors/no-location-assign-relative-destination.mdx

16.3.02.4 KB
Original Source

Prevent usage of location.assign() or location.href assignment to navigate to internal Next.js pages.

Why This Error Occurred

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.

Possible Ways to Fix It

During the render phase

Use redirect() from next/navigation:

tsx
import { redirect } from 'next/navigation'

export default function Page() {
  redirect('/dashboard')
}
tsx
'use client'

import { redirect } from 'next/navigation'

export default function MyComponent({
  isAuthorized,
}: {
  isAuthorized: boolean
}) {
  if (!isAuthorized) {
    redirect('/login')
  }
  return <div>Protected content</div>
}

In Client Components (event handlers)

Use useRouter().push() from next/navigation:

tsx
'use client'

import { useRouter } from 'next/navigation'

export default function MyButton() {
  const router = useRouter()

  return (
    <button onClick={() => router.push('/dashboard')}>Go to Dashboard</button>
  )
}

External URLs

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:

js
// 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

No Statically Analyzable Values

If the rule cannot statically determine whether a value is absolute or relative (e.g., function calls, event properties), the check is skipped:

js
// Skipped — cannot determine statically
const url = getUrl() // Function call
location.href = url

// Skipped — cannot determine statically
location.href = event.target.href