Parsing Key-Value URL Fragments with Node.JS

Although the URL fragment isn't defined explicitly as a key-value pair, there are times where it may be, for instance during the OAuth2 Implicit Grant or the OpenID Connect Hybrid Flow.

We can use the url module to actually parse our URL out, and then the querystring module to extract the key-value parameters for the fragment, instead of hand-rolling our own:

const url = require('url');
const querystring = require('querystring');
const theUrl = 'https://example.com/auth/callback#code=foo&state=blah';
var fragmentParams = querystring.parse(url.parse(theUrl).hash.replace('#', ''));
console.log(fragmentParams);
// Object: null prototype] { code: 'foo', state: 'blah' }

Also note that yes, this should be received by your browser, not by some Node code which runs on the backend, but for the purpose I've been testing it with, the Node code for it was important.

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

Tags
Related Posts

Other posts you may be interested in:

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.