Search code examples
reactjsnext.jsdownloadcors

How to download a video from tiktok cdn on button click with NextJS 13 (app) without getting cors error


So I am making a Tiktok downloader that downloads a Tiktok video. I already have an API that gets the URL of the video.

Here is the sample link A video from tiktok

This is my code for downloading the file

  const downloadFile = async (fileUrl: string) => {
    try {
      const data = await axios
        .get(fileUrl, {
          responseType: "blob",
        })
        .then((response) => {
          const url = window.URL.createObjectURL(new Blob([response.data]));
          const link = document.createElement("a");
          link.href = url;
          link.setAttribute("download", "file.mp4");
          document.body.appendChild(link);
          link.click();
        });


    } catch (error) {
      console.log(error);
    }
  };

However I am getting this error

Access to XMLHttpRequest at 'https://v39-dynamic-ceb1a.tiktokcdn.com/4b8b52de8905d9e8ec91e81ac5aa54f7/650d7dea/video/tos/alisg/tos-alisg-pve-0037/o81KAghoZBJxLAomBOvT3VwIzNAgfAQCpAFyGE/?a=1180&ch=0&cr=0&dr=0&lr=all&cd=0%7C0%7C0%7C0&cv=1&br=782&bt=391&bti=OHYpOTY0Zik7OzlmOm01MzE6ZC4xMDo%3D&cs=0&ds=3&ft=7b3-cDIENA7VQHgGYAuTLd.olY2p8lcywfuwyWHrK&mime_type=video_mp4&qs=0&rc=OWU2ZGZoZGU7OmRoZTw6PEBpajU5bTM6ZjxnbjMzODgzNEAwY2EvLi9jNS4xX2IyMzYvYSNuZmcxcjRnYy1gLS1kLy1zcw%3D%3D&l=202309220543147927725C85E05423B21D&btag=e00088000' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I tried adding withCredentials=true and withCredentials=false, but I still failed.


Solution

  • The only way to get access to videos legitimately from TikTok is to use their Research API: https://developers.tiktok.com/doc/about-research-api/

    Other than that CORS is there for a reason.