Adi
Adi2y ago

✅ – Adi – 11-00 Jan 23

[How to secure API routes in Nextjs]
Solution:
you need to use getserversession
Jump to solution
5 Replies
Adi
Adi2y ago
I am using this code snippet:
import nocountries from '../data/nocountries.json';
import countryList from "country-list";
import { getSession } from "next-auth";

export default async (req, res) => {
const session = await getSession({ req });
if (!session) {
return res.status(401).send({ Error: 'Unauthenticated User' });
}

if (req.method === 'GET') {
try {
const { country, filter } = req.query;
const code = countryList.getCode(country);

const result = nocountries[code].filter(item => item.target_type === filter);

res.status(200).send(result);
} catch (error) {
console.error("Error: ", error)
res.status(500).send({ message: "Failed" });
}
} else {
res.status(500).send({ message: "Internal Server Error" });
}
}
import nocountries from '../data/nocountries.json';
import countryList from "country-list";
import { getSession } from "next-auth";

export default async (req, res) => {
const session = await getSession({ req });
if (!session) {
return res.status(401).send({ Error: 'Unauthenticated User' });
}

if (req.method === 'GET') {
try {
const { country, filter } = req.query;
const code = countryList.getCode(country);

const result = nocountries[code].filter(item => item.target_type === filter);

res.status(200).send(result);
} catch (error) {
console.error("Error: ", error)
res.status(500).send({ message: "Failed" });
}
} else {
res.status(500).send({ message: "Internal Server Error" });
}
}
I am getting error: getSession) is not a function I used import { getSession } from "next-auth/client"; still it did not work. Any idea what I am missing?
Dawid
Dawid2y ago
get session is for client side
Solution
Dawid
Dawid2y ago
you need to use getserversession
reactibot
reactibot2y ago
This question has an answer! Thank you for helping 😄 If you have a followup question, you may want to reply to this thread so other members know they're related. https://discord.com/channels/102860784329052160/902647189120118794/1067035979904458793
reactibot
reactibot2y ago
This thread hasn’t had any activity in 12 hours, so it’s now locked. Threads are closed automatically after 12 hours. If you have a followup question, you may want to reply to this thread so other members know they're related. https://discord.com/channels/102860784329052160/902647189120118794/1067035979904458793 Question not getting answered? Maybe it's hard to answer, or maybe you asked at a slow time. Check out these resources for help asking a good question: https://stackoverflow.com/help/how-to-ask http://wp.me/p2oIwo-26