Skip to content

feat: add redirectStatusCode option#3685

Merged
BobbieGoede merged 10 commits intonuxt-modules:nextfrom
MarlonWiss2212:feature/add-custom-redirect-code
Jun 29, 2025
Merged

feat: add redirectStatusCode option#3685
BobbieGoede merged 10 commits intonuxt-modules:nextfrom
MarlonWiss2212:feature/add-custom-redirect-code

Conversation

@MarlonWiss2212
Copy link
Copy Markdown
Contributor

@MarlonWiss2212 MarlonWiss2212 commented Jun 8, 2025

🔗 Linked issue

No linked issue.

📚 Description

This PR introduces a new redirectCode option, allowing developers to specify the HTTP status code used for localization redirects (e.g., 303 for redirects). This adds flexibility to how redirects are handled.

This is my first contribution to nuxt-i18n, so please feel free to share any feedback or suggestions — I'd really appreciate it!

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Added support for configuring the HTTP status code used for redirects in internationalized routes.
    • Users can now specify a custom redirect status code in the options and runtime configuration.
  • Enhancements

    • Redirect behavior is now more customizable, allowing for improved control over navigation flows.
    • Fallback locale detection always occurs to ensure proper redirect handling.
  • Tests

    • Introduced tests to verify custom redirect status codes for root and non-root route redirects.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 8, 2025

Walkthrough

A new optional property, redirectStatusCode, has been introduced throughout the codebase to allow configuration and propagation of the HTTP status code used for redirects. This property is now present in options, runtime context, public runtime config, and is utilized during navigation to control redirect behavior. Additionally, server-side detection and redirect logic were updated to apply this status code when appropriate, and tests were added to verify the behavior.

Changes

File(s) Change Summary
src/constants.ts Added redirectStatusCode: 302 to DEFAULT_OPTIONS.
src/prepare/runtime-config.ts Added redirectStatusCode from options to nuxt.options.runtimeConfig.public.i18n.
src/runtime/context.ts Changed redirectStatusCode in NuxtI18nContext to required and initialized it in context.
src/runtime/utils.ts Modified navigate to pass { redirectCode: ctx.redirectStatusCode } to navigateTo.
src/types.ts Added redirectStatusCode to NuxtI18nOptions and I18nPublicRuntimeConfig types/interfaces.
docs/content/docs/04.api/00.options.md Added documentation for new redirectStatusCode option with default 302.
specs/routing_strategies/redirect_status_code.spec.ts Added new test suite verifying custom redirect status codes for root and non-root redirects.
src/runtime/server/plugin.ts Updated locale detection to always yield fallback and apply redirectStatusCode if no root redirect.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant App
    participant I18nContext
    participant RuntimeConfig
    participant Router

    User->>App: Initiates navigation
    App->>I18nContext: Retrieve redirectStatusCode
    I18nContext->>RuntimeConfig: Get redirectStatusCode from config
    App->>Router: navigateTo(destination, { redirectCode: redirectStatusCode })
    Router-->>User: Performs redirect with specified status code
Loading

Suggested labels

cr-tracked

Poem

In the warren of code, a new path appears,
Redirects now whisper their status in rabbit ears.
Options extended, context aware,
Hop to your language, with codes handled with care.
A leap for the hoppers, a hop for the crew—
Redirects made smarter, just for you!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bf68119 and 2c5b30c.

📒 Files selected for processing (3)
  • docs/content/docs/04.api/00.options.md (2 hunks)
  • src/constants.ts (1 hunks)
  • src/types.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • docs/content/docs/04.api/00.options.md
  • src/types.ts
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: test (lts/*, ubuntu-latest)
  • GitHub Check: test (lts/*, windows-latest)
  • GitHub Check: Redirect rules - nuxt-i18n-legacy
  • GitHub Check: Header rules - nuxt-i18n-legacy
  • GitHub Check: Pages changed - nuxt-i18n-legacy
🔇 Additional comments (1)
src/constants.ts (1)

65-65: LGTM! Well-positioned addition with appropriate default value.

The redirectStatusCode: 302 property is correctly placed after rootRedirect and uses an appropriate default. HTTP 302 (Found) is the standard choice for temporary redirects, which aligns well with i18n redirect behavior since language preferences can change dynamically.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/constants.ts (1)

64-64: Consider adding validation for HTTP redirect status codes.

The default value is appropriate. However, consider validating that when redirectStatusCode is provided, it's a valid HTTP redirect status code (e.g., 301, 302, 303, 307, 308).

Example validation could be added during option processing:

const validRedirectCodes = [301, 302, 303, 307, 308];
if (options.redirectStatusCode && !validRedirectCodes.includes(options.redirectStatusCode)) {
  throw new Error(`Invalid redirectStatusCode: ${options.redirectStatusCode}. Must be one of: ${validRedirectCodes.join(', ')}`);
}
src/types.ts (1)

174-174: Missing JSDoc for redirectStatusCode option
The new redirectStatusCode property should include a JSDoc comment explaining its purpose, default behavior when not set, and allowed HTTP status codes.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a37a7b4 and f45bd12.

📒 Files selected for processing (5)
  • src/constants.ts (1 hunks)
  • src/prepare/runtime-config.ts (1 hunks)
  • src/runtime/context.ts (2 hunks)
  • src/runtime/utils.ts (1 hunks)
  • src/types.ts (2 hunks)
🔇 Additional comments (4)
src/prepare/runtime-config.ts (1)

14-14: LGTM! Correct integration into runtime configuration.

The addition follows the established pattern for passing configuration options to the runtime config.

src/runtime/context.ts (2)

44-44: LGTM! Correct interface extension.

The type definition properly allows undefined which is consistent with the optional nature of this configuration.


105-105: LGTM! Proper initialization pattern.

The initialization follows the established pattern for other context properties.

src/types.ts (1)

360-360: Correctly exposed redirectStatusCode in public runtime config
The I18nPublicRuntimeConfig now properly includes the new option.

Comment thread src/runtime/utils.ts
}

return navigateTo(destination)
return navigateTo(destination, { redirectCode: ctx.redirectStatusCode })
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verify that navigateTo handles undefined redirectCode gracefully.

The implementation correctly uses the new redirectStatusCode option. The naming change from redirectStatusCode to redirectCode aligns with the navigateTo API.

Run the following script to verify the navigateTo function signature and confirm it properly handles undefined values for redirectCode:


🏁 Script executed:

#!/bin/bash
# Description: Verify navigateTo function signature and redirectCode parameter handling

# Search for navigateTo function definition and usage
rg -A 10 "function navigateTo|export.*navigateTo" --type ts
echo "---"
# Look for redirectCode parameter usage in navigateTo
rg -A 5 -B 5 "redirectCode" --type ts

Length of output: 1318


🌐 Web query:

What is the TypeScript signature of the navigateTo function in Nuxt 3? Specifically, what is the type of the redirectCode option parameter?

💡 Result:

TypeScript Signature of navigateTo in Nuxt 3

The navigateTo function in Nuxt 3 is used for programmatic navigation both on the server and client sides. Its TypeScript signature is as follows:

function navigateTo(
  to: RouteLocationRaw | undefined | null,
  options?: NavigateToOptions
): Promise<void | NavigationFailure | false> | false | void | RouteLocationRaw

interface NavigateToOptions {
  replace?: boolean
  redirectCode?: number
  external?: boolean
  open?: OpenOptions
}

type OpenOptions = {
  target: string
  windowFeatures?: OpenWindowFeatures
}

[1]

Type of the redirectCode Option

The redirectCode property in the NavigateToOptions interface is of type number. It allows you to specify the HTTP status code used for redirection when the navigation is handled on the server (for instance, during SSR or API requests). By default, Nuxt uses a status code of 302 (temporary redirect), but you can override it, for example, with 307 for a temporary redirect that preserves the request method, or 308 for a permanent redirect[1][6][7].

Example usage:

await navigateTo('/another-page', {
  redirectCode: 307
})

[6]

Summary Table

Option Type Description
redirectCode number HTTP status code for server-side redirects (e.g., 302, 307, 308)

The redirectCode is optional and only relevant in server-side navigation scenarios[1][6].

Citations:


Verified navigateTo Redirect Option

  • The navigateTo signature in Nuxt 3 declares options?: { redirectCode?: number; … }, so passing ctx.redirectStatusCode (even if undefined) is handled gracefully.
  • Suggest adding a simple validation to ensure ctx.redirectStatusCode is a valid HTTP status code (e.g. between 300 and 399, or 307/308) before passing it to navigateTo.

Affected location:

  • src/runtime/utils.ts line 289
🤖 Prompt for AI Agents
In src/runtime/utils.ts at line 289, the call to navigateTo passes
ctx.redirectStatusCode directly as redirectCode without validation. To fix this,
add a check to ensure ctx.redirectStatusCode is a valid HTTP redirect status
code (typically between 300 and 399, or specifically 307 or 308) before passing
it. If it is invalid or undefined, omit the redirectCode option or set it to a
default valid value to prevent potential unexpected behavior.

@BobbieGoede
Copy link
Copy Markdown
Member

Thank you for your PR!

This looks like a good option to add, as you have already noted we will need to add documentation and some tests before we can merge this 🙏

Also, this PR may get delayed a bit since I am working on changes that may overlap with it in #3687.

@MarlonWiss2212
Copy link
Copy Markdown
Contributor Author

Thank you for the info @BobbieGoede.
I added a little section in the docs and added 2 little tests.
Feel free to review it.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
specs/routing_strategies/redirect_status_code.spec.ts (1)

23-35: Solid test coverage for core functionality with room for enhancement.

The test cases effectively verify that:

  1. The new redirectStatusCode option works for general redirects
  2. Existing rootRedirect configuration remains unaffected

Consider adding these test scenarios for more comprehensive coverage:

  • Testing redirects with different source locales
  • Validating behavior with invalid status codes
  • Testing interaction with browser language detection when enabled
  test('does not affect root redirect option', async () => {
    const rootRes = await fetch('/', { redirect: 'manual' })
    expect(rootRes.status).toEqual(418)
    expect(rootRes.headers.get('location')).toEqual('/en/test-route')
  })
+
+  test('works with different source paths', async () => {
+    const res = await fetch('/contact', { redirect: 'manual' })
+    expect(res.status).toBe(307)
+    expect(res.headers.get('location')).toEqual('/en/contact')
+  })
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5a8d969 and 03b5460.

📒 Files selected for processing (1)
  • specs/routing_strategies/redirect_status_code.spec.ts (1 hunks)
🔇 Additional comments (1)
specs/routing_strategies/redirect_status_code.spec.ts (1)

6-21: Well-designed test setup for isolating the new feature.

The configuration effectively isolates the redirectStatusCode feature by disabling browser language detection and using distinct status codes (307 for general redirects vs 418 for root redirects) to verify that the new option works correctly without interfering with existing functionality.

@BobbieGoede BobbieGoede changed the title feat: add redirectStatusCode option feat: add redirectStatusCode option Jun 29, 2025
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/runtime/server/plugin.ts (1)

118-120: Implementation looks correct, but consider adding validation.

The implementation correctly applies the configured redirect status code when no root redirect is applicable. However, consider adding validation to ensure the redirectStatusCode is a valid HTTP status code.

-    } else if (runtimeI18n.redirectStatusCode) {
-      redirectCode = runtimeI18n.redirectStatusCode
+    } else if (runtimeI18n.redirectStatusCode) {
+      // Validate that it's a valid HTTP redirect status code (3xx)
+      if (runtimeI18n.redirectStatusCode >= 300 && runtimeI18n.redirectStatusCode < 400) {
+        redirectCode = runtimeI18n.redirectStatusCode
+      }
     }

Alternatively, validation could be performed at the configuration level rather than runtime for better performance.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fe18426 and bf68119.

📒 Files selected for processing (3)
  • specs/routing_strategies/redirect_status_code.spec.ts (1 hunks)
  • src/runtime/context.ts (2 hunks)
  • src/runtime/server/plugin.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/runtime/context.ts
  • specs/routing_strategies/redirect_status_code.spec.ts
🧰 Additional context used
🧠 Learnings (1)
src/runtime/server/plugin.ts (2)
Learnt from: BobbieGoede
PR: nuxt-modules/i18n#3587
File: src/runtime/plugins/route-locale-detect.ts:24-31
Timestamp: 2025-05-05T20:42:02.900Z
Learning: In nuxt-modules/i18n's route detection, the `detectLocale` function returns a string representing the locale code, not an object. This string can be passed directly to `ctx.setLocale`.
Learnt from: BobbieGoede
PR: nuxt-modules/i18n#3587
File: src/runtime/plugins/route-locale-detect.ts:24-31
Timestamp: 2025-05-05T20:42:02.900Z
Learning: In nuxt-modules/i18n's route detection, the `detectLocale` function returns a string representing the locale code, not an object. This string can be passed directly to `ctx.setLocale`.
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: test (lts/*, ubuntu-latest)
  • GitHub Check: test (lts/*, windows-latest)
  • GitHub Check: lint (lts/*, ubuntu-latest)
🔇 Additional comments (2)
src/runtime/server/plugin.ts (2)

41-42: LGTM: Good addition of fallback locale detection.

The addition of a fallback locale yield ensures that the detection process always has a fallback option available, improving the robustness of locale detection.


101-101: LGTM: Proper defensive programming with logical OR assignment.

Using the logical OR assignment operator to ensure locale defaults to defaultLocale when no supported locale is found is a good defensive programming practice.

@BobbieGoede
Copy link
Copy Markdown
Member

Thank you for updating the PR!

I have made some small changes and also modified the test to use the nitro context detection. The goal is to remove the option to disable nitro context detection in the future (just adding context why I did not add a separate fixture with it disabled).

@BobbieGoede BobbieGoede merged commit 2a18b32 into nuxt-modules:next Jun 29, 2025
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants