Grabbing URL before serving Dash layout


Hi Chris,

We were wondering if there was some way to grab the URL before serving the Dash app layout. We are currently setting app.layout to a function (as seen in your tutorial here:, but need this URL to update a component within the layout.

def serve_layout():

   # We need to grab the URL here to update a component below
   # We tried url_string = request.url here, but failed (see below)

   return html.Div([ ... ])

app.layout = serve_layout()

Ideally, we would use the dcc.Location component to grab the URL through ‘pathname,’ however, this component is not initialized yet. We thought to use Flask’s request.url function, but this is not accessible from this function (error: RuntimeError: Working outside of request context.). How can we access the request? Or any other ideas to get this URL?




If you render your content dynamically using dcc.Location and dcc.Link then your callback function that renders the content will be called on every page load and on every new URL automatically - you won’t need serve_layout anymore.

Adapting from the example here:

app.layout = html.Div([
    # represents the URL bar, doesn't render anything
    dcc.Location(id='url', refresh=False),

    # content will be rendered in this element

@app.callback(dash.dependencies.Output('page-content', 'children'),
              [dash.dependencies.Input('url', 'pathname')])
def display_page(pathname):
    # this is called every page load and every URL change
    # you can update your components with this URL in here
    return html.Div([
        html.H3('You are on page {}'.format(pathname))


Hi @chriddyp,

Thanks, this was really helpful! It seems to be an error with no consequences, but I’m noticing that dcc.Location initializes its pathname as None in the beginning. The callback seems to be firing multiple times upon browser open, where the first time pathname=None, and then subsequent times it’s correct with the URL.


Jonathan Hsu


@jyhsu - Yeah, that’s done for a couple of reasons, see for more details.

So, what you can do is either return 'Loading...' or simply '' when pathname is None. It’ll get called after everything renders again with the proper pathname.