← All posts

Moving Spotify Liked Songs to YouTube Music

November 4, 2026

Fist of all Why bother? because when I drive my wife is my DJ and she has all of her favourite songs on Spotify which sucks without premium and I already have YouTube premium soooo.. all of this is just to vibe hard when driving

Couple of days ago I moved my YouTube subscriptions to my new account using nothing but the browser console (again because of the premium account). It worked, I felt like a genius for about ten minutes.

She has 509 liked songs, sitting on an app she barely opens anymore because the free tier renders the app virtually useless. I was being lazy about it for a long time but enough free time helps you run these side quests, so here we are.

The plan was simple. Copy the same trick. Console, cookies, no official API, no Google Cloud project, no drama.

Obviously that is not how it went.

The Plan

  1. Get all her liked songs out of Spotify.

  2. Search each one on YouTube Music.

  3. Put the matches in a new playlist.

  4. If a song is a remix, a live version, or just not there, don’t add something random. Skip it and keep a list so I can find it by hand.

  5. Don’t make it re-do everything if it dies halfway.

  6. Pretend this was a carefully planned engineering project (Most important).

The Only Complicated Part: Getting Out of Spotify

YouTube was the easy side because I had already done the cookie trick before. Spotify was the problem.

My first idea was the lazy one. Spotify’s web player already has a login token, so I grabbed it from the page and called /v1/me/tracks myself. 509 songs is only 11 requests of 50 each.

Spotify said no.

429 Too Many Requests (from service worker)

On the very first request. Not the eleventh, the first. I waited, tried again, same thing. Turns out the web player’s token is shared and throttled and I was basically knocking on a door that was already being kicked by everyone.

The proper fix was creating my own Spotify developer app. The other fix was an export website that does it with one click. I didn’t want to do either.

I don’t want to create an app, and I definitely don’t want to log into some random website and hand it my entire library. So the honest answer was: if the API won’t talk to me, I’ll just read the page like a human does.

Step 1: Export (Spotify)

Open open.spotify.com/collection/tracks, open the console, and paste this. If Chrome complains, type allow pasting first.

(async () => {
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
  const rows = () => [...document.querySelectorAll('[data-testid="track-row"]')];
  if (!rows().length) throw new Error('No track-row elements. Open open.spotify.com/collection/tracks.');

  // scroll the page until the infinite list stops growing
  window.scrollTo(0, 0); await sleep(800);
  let stable = 0, last = -1;
  while (stable < 6) {
    window.scrollBy(0, innerHeight * 0.8);
    await sleep(600);
    const n = rows().length;
    const atBottom = innerHeight + scrollY >= document.scrollingElement.scrollHeight - 5;
    if (n === last && atBottom) stable++; else stable = 0;
    last = n;
    console.log('Rows loaded: ' + n);
  }

  const all = rows().map((r) => {
    const title = (r.getAttribute('aria-label') || '').trim();
    const a = (r.querySelector('[data-encore-id="text"]')?.textContent || '').trim();
    return { title, artists: a ? a.split(/,\s+/) : [], album: '', durationMs: null };
  });
  const tracks = all.filter((t) => t.title);
  const skipped = all.length - tracks.length;
  if (skipped) console.warn(skipped + ' rows were blank (unavailable/greyed-out songs) and were skipped.');

  const a = document.createElement('a');
  a.href = URL.createObjectURL(new Blob([JSON.stringify(tracks, null, 2)], { type: 'application/json' }));
  a.download = 'liked-songs.json';
  a.click();
  console.log('Done. ' + tracks.length + ' songs saved (of ' + all.length + ' rows).');
})();

It scrolls the list over and over because Spotify only loads the rows you can see, then it reads whatever is on the page. No token, no API, nothing to rate limit.

It took a few attempts to find the right thing to read. Spotify keeps renaming its own markup, so the first two versions found zero rows and yelled at me. The final one reads the aria-label of each row for the title, which is a bit of a hack but it works.

It gives you a liked-songs.json with the title and artists of every song. No album, no duration, because the page doesn’t make those easy to grab.

That last part matters later.

Step 2: Import (YouTube Music)

Now go to music.youtube.com on the Premium account, open the console, and paste this one. It opens a button at the top of the page for choosing the JSON file.

(async () => {
  const ORIGIN = 'https://music.youtube.com';
  const STORE = 'sp2yt_state_v1';
  const SONGS_FILTER = 'EgWKAQIIAWoKEAkQBRAKEAMQBA%3D%3D';
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
  const jitter = () => sleep(1500 + Math.random() * 1000);

  const cfg = window.ytcfg;
  const KEY = cfg.get('INNERTUBE_API_KEY');
  const CONTEXT = cfg.get('INNERTUBE_CONTEXT');
  const AUTHUSER = String(cfg.get('SESSION_INDEX') || 0);

  async function authHeader() {
    const m = document.cookie.match(/(?:^|;\s*)SAPISID=([^;]+)/);
    if (!m) throw new Error('Not logged in? SAPISID cookie missing.');
    const ts = Math.floor(Date.now() / 1000);
    const buf = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(`${ts} ${m[1]} ${ORIGIN}`));
    const hex = [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, '0')).join('');
    return `SAPISIDHASH ${ts}_${hex}`;
  }

  async function api(path, body) {
    const res = await fetch(`${ORIGIN}/youtubei/v1/${path}?key=${KEY}&prettyPrint=false`, {
      method: 'POST',
      credentials: 'include',
      headers: {
        'Content-Type': 'application/json',
        Authorization: await authHeader(),
        'X-Origin': ORIGIN,
        'X-Goog-AuthUser': AUTHUSER,
      },
      body: JSON.stringify({ context: CONTEXT, ...body }),
    });
    if (!res.ok) throw new Error('HTTP ' + res.status);
    return res.json();
  }

  // ----- helpers -----
  const norm = (s) =>
    (s || '')
      .normalize('NFKD').replace(/[̀-ͯ]/g, '')
      .toLowerCase()
      .replace(/\s*[\(\[][^)\]]*(feat|ft|with)\.?[^)\]]*[\)\]]/g, '')
      .replace(/\s+-\s+(feat|ft)\.?.*$/, '')
      .replace(/&/g, 'and')
      .replace(/[^a-z0-9ऀ-ॿ਀-੿ ]+/g, ' ')
      .replace(/\s+/g, ' ')
      .trim();

  // Words that mark a different version of the song; they must agree on both sides.
  const VERSION_WORDS = ['remix', 'live', 'acoustic', 'instrumental', 'karaoke', 'cover', 'sped up', 'slowed', 'reverb', 'lofi', 'lo fi', 'remaster', 'remastered', 'mashup', 'edit', 'version', 'demo', 'unplugged', 'reprise', 'extended', 'radio edit', 'cut'];
  const versionSet = (s) => {
    const n = ' ' + norm((s || '').replace(/[\(\)\[\]\-]/g, ' ')) + ' ';
    return VERSION_WORDS.filter((w) => n.includes(' ' + w + ' ')).sort().join('|');
  };
  const stripVersion = (s) => norm(s.replace(/[\(\[][^)\]]*[\)\]]/g, ' ').replace(/\s-\s.*$/, ''));

  const parseDur = (s) => {
    const p = (s || '').split(':').map(Number);
    return p.some(isNaN) ? null : p.reduce((a, n) => a * 60 + n, 0);
  };
  const keyOf = (t) => `${t.title}|${t.artists.join(',')}|${t.durationMs}`;

  function parseCandidates(json) {
    const out = [];
    (function walk(n) {
      if (!n || typeof n !== 'object') return;
      if (n.musicResponsiveListItemRenderer) {
        const r = n.musicResponsiveListItemRenderer;
        try {
          const c0 = r.flexColumns[0].musicResponsiveListItemFlexColumnRenderer.text.runs;
          const c1 = r.flexColumns[1].musicResponsiveListItemFlexColumnRenderer.text.runs.map((x) => x.text).join('');
          const videoId = (r.playlistItemData && r.playlistItemData.videoId) || (c0[0].navigationEndpoint && c0[0].navigationEndpoint.watchEndpoint && c0[0].navigationEndpoint.watchEndpoint.videoId);
          const parts = c1.split(' • ');
          const last = parts[parts.length - 1];
          if (videoId) out.push({ videoId, title: c0[0].text, artists: parts[0], duration: parseDur(last) });
        } catch (e) {}
        return;
      }
      for (const k in n) walk(n[k]);
    })(json);
    return out;
  }

  function isMatch(t, c) {
    // Duration is only checked when the Spotify export has it (the page scrape does not).
    if (t.durationMs && (c.duration == null || Math.abs(c.duration - t.durationMs / 1000) > 4)) return false;
    if (versionSet(t.title) !== versionSet(c.title)) return false;
    const a = stripVersion(t.title), b = stripVersion(c.title);
    if (!a || !b || !(a === b || a.includes(b) || b.includes(a))) return false;
    const ca = norm(c.artists);
    return t.artists.some((x) => ca.includes(norm(x))) || norm(c.title).includes(norm(t.artists[0]));
  }

  async function findVideo(t) {
    const q = `${t.title} ${t.artists.join(' ')}`;
    const json = await api('search', { query: q, params: decodeURIComponent(SONGS_FILTER) });
    const cands = parseCandidates(json).slice(0, 6);
    const hit = cands.find((c) => isMatch(t, c));
    return hit ? hit.videoId : null;
  }

  const download = (name, text, type) => {
    const a = document.createElement('a');
    a.href = URL.createObjectURL(new Blob([text], { type }));
    a.download = name;
    a.click();
  };
  const csvCell = (v) => '"' + String(v ?? '').replace(/"/g, '""') + '"';

  // ----- load input -----
  const tracks = await new Promise((resolve) => {
    const btn = document.createElement('button');
    btn.textContent = 'Choose liked-songs.json';
    btn.style.cssText = 'position:fixed;top:80px;left:50%;transform:translateX(-50%);z-index:999999;padding:14px 22px;font-size:16px;background:#fff;color:#000;border:2px solid #f03;border-radius:8px;cursor:pointer';
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.json,application/json';
    input.onchange = async () => {
      resolve(JSON.parse(await input.files[0].text()));
      btn.remove();
    };
    btn.onclick = () => input.click();
    document.body.appendChild(btn);
    console.log('Click the "Choose liked-songs.json" button at the top of the page.');
  });
  console.log(`Loaded ${tracks.length} tracks.`);

  // ----- state -----
  let state;
  try { state = JSON.parse(localStorage.getItem(STORE)); } catch (e) {}
  if (!state || state.total !== tracks.length) {
    const name = prompt('New playlist name:', "Mimu's Spotify");
    if (!name) throw new Error('Cancelled.');
    state = { total: tracks.length, name, playlistId: null, matched: {}, unmatched: {}, added: 0 };
  }
  const save = () => { try { localStorage.setItem(STORE, JSON.stringify(state)); } catch (e) {} };

  // ----- phase 1: match -----
  let stopped = false;
  for (let i = 0; i < tracks.length; i++) {
    const t = tracks[i], k = keyOf(t);
    if (k in state.matched || k in state.unmatched) continue;
    try {
      const vid = await findVideo(t);
      if (vid) state.matched[k] = vid;
      else state.unmatched[k] = 'no exact match (remix/live/other version or not on YT Music)';
      console.log(`[${i + 1}/${tracks.length}] ${vid ? 'OK  ' : 'MISS'} ${t.artists[0]} - ${t.title}`);
    } catch (e) {
      console.warn(`[${i + 1}/${tracks.length}] error: ${e.message}`);
      if (/429/.test(e.message)) { console.warn('Rate limited, stopping. Wait a while and re-run.'); stopped = true; save(); break; }
      state.unmatched[k] = 'error: ' + e.message;
    }
    save();
    await jitter();
  }

  // ----- phase 2: playlist + add -----
  if (!stopped) {
    const ids = [];
    for (const t of tracks) { const v = state.matched[keyOf(t)]; if (v) ids.push(v); }
    try {
      if (!state.playlistId) {
        const r = await api('playlist/create', { title: state.name, description: 'Imported from Spotify Liked Songs', privacyStatus: 'PRIVATE', videoIds: [] });
        state.playlistId = r.playlistId;
        if (!state.playlistId) throw new Error('playlist/create returned no id');
        save();
        console.log('Created playlist ' + state.playlistId);
      }
      for (let i = state.added; i < ids.length; i += 50) {
        const batch = ids.slice(i, i + 50);
        await api('browse/edit_playlist', {
          playlistId: state.playlistId,
          actions: batch.map((v) => ({ action: 'ACTION_ADD_VIDEO', addedVideoId: v, dedupeOption: 'DEDUPE_OPTION_SKIP' })),
        });
        state.added = i + batch.length;
        save();
        console.log(`Added ${state.added}/${ids.length}`);
        await jitter();
      }
      console.log(`Done. ${ids.length} songs in https://music.youtube.com/playlist?list=${state.playlistId}`);
    } catch (e) {
      console.warn('Adding stopped: ' + e.message + '. Re-run to resume.');
      stopped = true;
    }
  }

  // ----- unmatched report -----
  const rows = tracks.filter((t) => keyOf(t) in state.unmatched);
  if (rows.length) {
    const csv = ['title,artists,album,reason,search_link']
      .concat(rows.map((t) => [t.title, t.artists.join('; '), t.album, state.unmatched[keyOf(t)],
        `${ORIGIN}/search?q=${encodeURIComponent(t.title + ' ' + t.artists[0])}`].map(csvCell).join(',')))
      .join('\n');
    download('unmatched.csv', csv, 'text/csv');
    console.log(`${rows.length} songs need manual adding; see unmatched.csv`);
  }
  if (!stopped) console.log('To start fresh next time: localStorage.removeItem("' + STORE + '")');
})();

It does the same cookie trick as the subscriptions one, builds the SAPISIDHASH in the browser, and talks to YouTube Music’s internal endpoints as me. Then for every song it does a search restricted to the Songs tab, looks at the top few results and only accepts one if the title and artist actually match.

That is the part I was most paranoid about, so here is what it refuses to match:

  • Anything where one side says remix, live, acoustic, slowed, reverb, karaoke, and so on, and the other side doesn’t.

  • Anything where the title doesn’t line up after stripping brackets and “feat.” bits.

  • Anything where none of the artists show up.

If it’s not sure, it skips. I would rather add 400 right songs and fix 100 by hand than add 509 songs and spend a week finding the wrong ones.

The skipped ones go into an unmatched.csv at the end, with a search link for each, so fixing them is just clicking through a list.

Also, that jitter() is intentional. A random 1.5 to 2.5 second wait between searches. Is it fooling YouTube into thinking I’m a human? Probably not. But at least I’m being polite.

It saves its progress in localStorage after every single song, so if it dies or YouTube gets annoyed, you paste it again and it carries on from where it stopped instead of starting over.

What Happened

  • Songs exported from Spotify: 509

  • Matched and added: 490

  • Skipped and put in unmatched.csv: 19

  • Time taken: roughly 30 minutes, mostly just waiting

Then I opened the unmatched list and spent a few minutes adding the leftovers by hand, which was honestly the most “normal” part of the whole thing.

Learnings

  • If an API says 429 on the very first request, it is not you, it is everyone.

  • Not wanting to create a developer app is a valid reason to spend three hours on a workaround.

  • Reading the page is slower than calling the API, but nobody can rate limit you for looking at a webpage.

  • A strict match rule is annoying right up until the moment it saves you from a nightclub remix in your study playlist.

  • Spotify changes its HTML way more often than I change my mind.

And honestly, I didn’t plan any of the above.

Built with a browser console, a stubborn refusal to make an account on anything, and a questionable amount of confidence.

If Spotify or YouTube changes something tomorrow and this stops working, I accept no responsibility. I barely accepted responsibility when it worked.

Read more of my shenanigans on Medium

tudulu ;]


Originally published on Medium.