**Redirecting Issue with Shortened URLs - Possible Database/Query Issue**
Unanswered
Hovawart posted this in #help-forum
HovawartOP
I’m facing an issue with the URL shortening feature in my application. it work fine in localhost, Specifically, valid shortCode entries are sometimes redirecting to incorrect URLs. I suspect there might be an issue with the way the database is handling the shortCode field or how the query logic is retrieving the URLs.
Here’s a quick summary of the problem:
Problem: When a user tries to access a shortened URL (e.g., https://shorty-sigma.vercel.app/73E8YKP), the app redirects to the wrong URL instead of original URL. (NAVIGATING TO SAME WEBSITE/URL THAT GENERATED THE CODE) What I’ve Checked: The shortCode entries in the database appear to be correct. Environment variables seem to be set up correctly since authentication and other features are working fine. The URL shortening process generates and saves shortCode as expected, but the retrieval goes wrong. developing with nextjs deployed to vercel.
pages/[shortCode].tsx
Here’s a quick summary of the problem:
Problem: When a user tries to access a shortened URL (e.g., https://shorty-sigma.vercel.app/73E8YKP), the app redirects to the wrong URL instead of original URL. (NAVIGATING TO SAME WEBSITE/URL THAT GENERATED THE CODE) What I’ve Checked: The shortCode entries in the database appear to be correct. Environment variables seem to be set up correctly since authentication and other features are working fine. The URL shortening process generates and saves shortCode as expected, but the retrieval goes wrong. developing with nextjs deployed to vercel.
pages/[shortCode].tsx
export const getServerSideProps: GetServerSideProps = async (context) => {
try {
await dbConnect();
const { shortCode } = context.params;
const urlEntry = await Url.findOne({ shortCode }).exec();
if (urlEntry) {
const originalUrl = urlEntry.originalUrl.startsWith('http')
? urlEntry.originalUrl
:http://${urlEntry.originalUrl};
console.log('Redirecting to:', originalUrl);
return {
redirect: {
destination: originalUrl,
permanent: false,
},
};
1 Reply
Original message was deleted
HovawartOP
pages/api/shorten.ts
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
await dbConnect();
// The code fetches the original URL from the database
if (req.method === 'POST') {
const { originalUrl, customDomain, customUrl } = req.body;
if (!originalUrl typeof originalUrl !== 'string') {
return res.status(400).json({ error: 'Invalid URL' });
}
try {
// he nanoid library is used to generate a short code.
// The base URL is determined by checking if the environment is production
let shortCode = customUrl nanoid(7);
const baseUrl = process.env.NODE_ENV === 'production'
? process.env.NEXTAUTH_URL
: 'http://localhost:3000';
const shortUrl = customDomain
?
:
// generates a QR code for the shortened URL.
const qrCode = await QRCode.toDataURL(shortUrl);
const newUrl = new Url({
originalUrl,
shortUrl,
shortCode,
qrCode,
});
await newUrl.save();
res.status(201).json({ message: 'URL shortened successfully', shortUrl, qrCode });
} catch (error) {
console.error('Error saving URL:', error);
res.status(500).json({ message: 'Internal Server Error' });
}
} else {
res.status(405).json({ message: 'Method not allowed' });
}
}
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
await dbConnect();
// The code fetches the original URL from the database
if (req.method === 'POST') {
const { originalUrl, customDomain, customUrl } = req.body;
if (!originalUrl typeof originalUrl !== 'string') {
return res.status(400).json({ error: 'Invalid URL' });
}
try {
// he nanoid library is used to generate a short code.
// The base URL is determined by checking if the environment is production
let shortCode = customUrl nanoid(7);
const baseUrl = process.env.NODE_ENV === 'production'
? process.env.NEXTAUTH_URL
: 'http://localhost:3000';
const shortUrl = customDomain
?
${customDomain}/${shortCode}:
${baseUrl}/${shortCode};// generates a QR code for the shortened URL.
const qrCode = await QRCode.toDataURL(shortUrl);
const newUrl = new Url({
originalUrl,
shortUrl,
shortCode,
qrCode,
});
await newUrl.save();
res.status(201).json({ message: 'URL shortened successfully', shortUrl, qrCode });
} catch (error) {
console.error('Error saving URL:', error);
res.status(500).json({ message: 'Internal Server Error' });
}
} else {
res.status(405).json({ message: 'Method not allowed' });
}
}