Skip to content

๐Ÿ”€ย ย Redirect

Submitted by Lukas Masuch

Summary

Programmatically redirect users to external or internal URLs.

Functions

redirect

Redirect the browser to a specified URL.

This component triggers a browser redirect to an external or internal URL. It's useful for OAuth flows, conditional navigation, or routing users based on application state.

Parameters:

Name Type Description Default
url str

The URL to redirect to. Must use http://, https://, or be a relative path starting with /.

required
target Literal['_self', '_blank']

Where to open the URL. Use "_self" (default) to redirect the current tab, or "_blank" to open in a new tab.

'_self'
replace_history bool

If True, replaces the current browser history entry instead of adding a new one. Useful for OAuth flows where you don't want users to navigate back to an incomplete auth state. Only applies when target is "_self". Default is False.

False

Example:

```python
if st.button("Go to GitHub"):
    redirect("https://github.com/streamlit/streamlit")
```
Note
  • For same-tab redirects (_self), the Streamlit app will be replaced
  • For new-tab redirects (_blank), popup blockers may prevent the action
  • URLs are validated to prevent javascript: and other unsafe schemes
  • A ValueError is raised if the URL is empty or uses an unsafe scheme
Source code in src/streamlit_extras/redirect/__init__.py
@extra
def redirect(
    url: str,
    *,
    target: Literal["_self", "_blank"] = "_self",
    replace_history: bool = False,
) -> None:
    """Redirect the browser to a specified URL.

    This component triggers a browser redirect to an external or internal URL.
    It's useful for OAuth flows, conditional navigation, or routing users
    based on application state.

    Args:
        url: The URL to redirect to. Must use http://, https://, or be a
            relative path starting with /.
        target: Where to open the URL. Use "_self" (default) to redirect the
            current tab, or "_blank" to open in a new tab.
        replace_history: If True, replaces the current browser history entry
            instead of adding a new one. Useful for OAuth flows where you
            don't want users to navigate back to an incomplete auth state.
            Only applies when target is "_self". Default is False.

    Example:

        ```python
        if st.button("Go to GitHub"):
            redirect("https://github.com/streamlit/streamlit")
        ```

    Note:
        - For same-tab redirects (_self), the Streamlit app will be replaced
        - For new-tab redirects (_blank), popup blockers may prevent the action
        - URLs are validated to prevent javascript: and other unsafe schemes
        - A ValueError is raised if the URL is empty or uses an unsafe scheme
    """
    validated_url = _validate_url(url)

    # Use st._event container to avoid adding any visual space to the UI
    with st._event:
        _REDIRECT_COMPONENT(
            data={
                "url": validated_url,
                "target": target,
                "replace_history": replace_history,
                "request_id": 1,
            },
            width="stretch",
            height=0,
        )

Import:

from streamlit_extras.redirect import redirect # (1)!
  1. You should add this to the top of your .py file ๐Ÿ› 

Examples

example_same_tab

def example_same_tab() -> None:
    """Example: Redirect in the same tab."""
    st.write("Click the button to redirect to the Streamlit GitHub repository.")

    if st.button("Go to Streamlit GitHub", key="redirect_same_tab"):
        redirect("https://github.com/streamlit/streamlit")

example_new_tab

def example_new_tab() -> None:
    """Example: Open URL in a new tab."""
    st.write("Click the button to open the Streamlit docs in a new tab.")

    if st.button("Open Streamlit Docs", key="redirect_new_tab"):
        redirect("https://docs.streamlit.io", target="_blank")

example_oauth_flow

def example_oauth_flow() -> None:
    """Example: OAuth-style redirect that replaces history."""
    st.write(
        "This demonstrates an OAuth-style redirect that replaces the browser history, "
        "preventing users from navigating back to an incomplete auth state."
    )

    if st.button("Simulate OAuth Redirect", key="redirect_oauth"):
        # In a real app, this would redirect to an OAuth provider
        redirect("https://example.com/oauth/authorize", replace_history=True)

example_conditional

def example_conditional() -> None:
    """Example: Conditional redirect based on user input."""
    st.write("Enter a search query and press Enter to search on Google.")

    query = st.text_input("Search query", key="search_query")
    if query:
        # URL-encode the query for safe use in the URL
        from urllib.parse import quote

        search_url = f"https://www.google.com/search?q={quote(query)}"
        if st.button("Search", key="redirect_search"):
            redirect(search_url, target="_blank")