Last active
July 11, 2022 16:10
-
-
Save arafathusayn/f4a294a54b2b099ae45576af9161e185 to your computer and use it in GitHub Desktop.
Vercel Serverless Function for getting redirected URL from short-link services
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import got from "got"; | |
import { VercelRequest, VercelResponse } from "@vercel/node"; | |
const redirect = async (request: VercelRequest, response: VercelResponse) => { | |
const url: string | undefined = | |
(request.query && request.query.url) || (request.body && request.body.url); | |
if ( | |
(request.method === "GET" || request.method === "POST") && | |
typeof url === "string" && | |
(url.startsWith("http://") || url.startsWith("https://")) | |
) { | |
const redirectedUrlResponse = await got(url, { method: "GET" }).catch( | |
(e) => { | |
console.error(e); | |
return null; | |
} | |
); | |
if (redirectedUrlResponse) { | |
return response.redirect(redirectedUrlResponse.url); | |
} else { | |
return response.status(500).send("Server Error"); | |
} | |
} | |
return response.status(400).send("Invalid Request"); | |
}; | |
export default redirect; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment