Revaycolizer
Revaycolizer
Explore posts from servers
NNuxt
Created by Revaycolizer on 11/2/2024 in #❓・help
My UI won't update even though I successfully receive response
I have this code below I successfully get the response but the UI won't update I still see no data available
<script setup lang="ts">
import { ref } from 'vue';

const name = ref('');
const number = ref(0);
const data = ref([]);

async function submit() {
try {

const response = await $fetch('/api/data', {
method: 'POST',
body: { test: 123, name: name.value, number: number.value },
});

console.log("Response from API:", response);

data.value = Array.isArray(response) ? response : [response];

console.log("Updated data:", data.value);
} catch (error) {
console.error("Error fetching data:", error);
data.value = [];
}
}
</script>

<template>
<input type="number" v-model.number="number" placeholder="Enter a number" />
<input type="text" v-model.trim="name" placeholder="Enter a name" />
<button @click="submit">Submit</button>


<div v-if="data.value && data.value.length > 0">
<div v-for="(da, index) in data" :key="index">
<p>{{ da.test || da }}</p>
</div>
</div>

<div v-else>
<p>No data available</p>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';

const name = ref('');
const number = ref(0);
const data = ref([]);

async function submit() {
try {

const response = await $fetch('/api/data', {
method: 'POST',
body: { test: 123, name: name.value, number: number.value },
});

console.log("Response from API:", response);

data.value = Array.isArray(response) ? response : [response];

console.log("Updated data:", data.value);
} catch (error) {
console.error("Error fetching data:", error);
data.value = [];
}
}
</script>

<template>
<input type="number" v-model.number="number" placeholder="Enter a number" />
<input type="text" v-model.trim="name" placeholder="Enter a name" />
<button @click="submit">Submit</button>


<div v-if="data.value && data.value.length > 0">
<div v-for="(da, index) in data" :key="index">
<p>{{ da.test || da }}</p>
</div>
</div>

<div v-else>
<p>No data available</p>
</div>
</template>
11 replies
TTCTheo's Typesafe Cult
Created by Revaycolizer on 7/6/2024 in #questions
Unable to upload files after deploying on vercel
This is how I implemented it but, does not seem to work as I get an error stating that no such file or directory '/vercel'
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.join(__filename);;

const directoryPath = path.resolve(__dirname, 'public');
const body = await req.formData()

const file = body.get("file") as File;

const buffer = Buffer.from(await file.arrayBuffer());
const relativeUploadDir = `/uploads`

const uploadDir = path.join(process.cwd(), relativeUploadDir);

console.log(uploadDir)
console.log(file.type)

try {
await stat(uploadDir);
} catch (e: any) {
if (e.code === "ENOENT") {
// This is for checking the directory is exist (ENOENT : Error No Entry)
await mkdir(uploadDir, { recursive: true });
} else {
console.error(
"Error while trying to create directory when uploading a file\n",
e
);
return NextResponse.json(
{ error: "Something went wrong." },
{ status: 500 }
);
}
}
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.join(__filename);;

const directoryPath = path.resolve(__dirname, 'public');
const body = await req.formData()

const file = body.get("file") as File;

const buffer = Buffer.from(await file.arrayBuffer());
const relativeUploadDir = `/uploads`

const uploadDir = path.join(process.cwd(), relativeUploadDir);

console.log(uploadDir)
console.log(file.type)

try {
await stat(uploadDir);
} catch (e: any) {
if (e.code === "ENOENT") {
// This is for checking the directory is exist (ENOENT : Error No Entry)
await mkdir(uploadDir, { recursive: true });
} else {
console.error(
"Error while trying to create directory when uploading a file\n",
e
);
return NextResponse.json(
{ error: "Something went wrong." },
{ status: 500 }
);
}
}
3 replies
TTCTheo's Typesafe Cult
Created by Revaycolizer on 10/17/2023 in #questions
Conditional Rendering problem
I am having trouble when a user likes he/she cannot unlike the post thus causing undefined value to be sent to the API endpoint using source code below
"use client"
export default function Comment () {
const {data,isLoading}=useSWR('/api/login',fetcher)

const [liked, setLiked] = useState(false)

const handleLike = async()=>{
try {
// Perform API call to add like
await axios.post("/api/like/", {
postId: post.id,
});
setLiked((prevLiked) => !prevLiked);
router.refresh();

} catch (error) {
console.log("Error adding like", error);
}
}

const handleRemoveLike = async()=>{
try {
// Perform API call to remove like
const updatedLikes = likes.filter((like: { userId: any; }) => like.userId == data?.id);
console.log(updatedLikes)
await axios.delete(`/api/like/${updatedLikes[0].id}`);

router.refresh();
setLiked((prevLiked) => !prevLiked);
} catch (error) {
console.log("Error removing like", error);
}
}

return(
<div className='px-8 py-4 flex flex-row justify-between'>
{likes.some((like:any) => like.userId === data?.id) || liked? (
<AiFillHeart size={24} onClick={handleRemoveLike} />
) : (
<AiOutlineHeart size={24} onClick={handleLike} />
)}{post.likes.length}{' '} <FaRegCommentDots size={24} onClick={() => setShowComments(!showComments)} />{post.comments.length}{' '}<IoMdShareAlt size={24} onClick={handleShare}/></div>
)
}
"use client"
export default function Comment () {
const {data,isLoading}=useSWR('/api/login',fetcher)

const [liked, setLiked] = useState(false)

const handleLike = async()=>{
try {
// Perform API call to add like
await axios.post("/api/like/", {
postId: post.id,
});
setLiked((prevLiked) => !prevLiked);
router.refresh();

} catch (error) {
console.log("Error adding like", error);
}
}

const handleRemoveLike = async()=>{
try {
// Perform API call to remove like
const updatedLikes = likes.filter((like: { userId: any; }) => like.userId == data?.id);
console.log(updatedLikes)
await axios.delete(`/api/like/${updatedLikes[0].id}`);

router.refresh();
setLiked((prevLiked) => !prevLiked);
} catch (error) {
console.log("Error removing like", error);
}
}

return(
<div className='px-8 py-4 flex flex-row justify-between'>
{likes.some((like:any) => like.userId === data?.id) || liked? (
<AiFillHeart size={24} onClick={handleRemoveLike} />
) : (
<AiOutlineHeart size={24} onClick={handleLike} />
)}{post.likes.length}{' '} <FaRegCommentDots size={24} onClick={() => setShowComments(!showComments)} />{post.comments.length}{' '}<IoMdShareAlt size={24} onClick={handleShare}/></div>
)
}
2 replies
TTCTheo's Typesafe Cult
Created by Revaycolizer on 10/5/2023 in #questions
Consuming API's created by nextjs
Consuming API's create by nextjs in flutter but getting this error Check no 'Access-Control-Allow-Origin' header is present on the requested resource. Below is the source code of my next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
async headers() {
return [
{
// matching all API routes
source: "/api/:path*",
headers: [
{ key: "Access-Control-Allow-Credentials", value: "true" },
{ key: "Access-Control-Allow-Origin", value: "*" }, // replace this your actual origin
{ key: "Access-Control-Allow-Methods", value: "GET,DELETE,PATCH,POST,PUT" },
{ key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
]
}
]
}
}

module.exports = nextConfig
/** @type {import('next').NextConfig} */
const nextConfig = {
async headers() {
return [
{
// matching all API routes
source: "/api/:path*",
headers: [
{ key: "Access-Control-Allow-Credentials", value: "true" },
{ key: "Access-Control-Allow-Origin", value: "*" }, // replace this your actual origin
{ key: "Access-Control-Allow-Methods", value: "GET,DELETE,PATCH,POST,PUT" },
{ key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
]
}
]
}
}

module.exports = nextConfig
Also my route handler I'm consuming
const response = {
message: "Authenticated!",
};

const seralized = serialize(COOKIE_NAME, JSON.stringify(userData), {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "strict",
maxAge: MAX_AGE,
path: "/",
});

return new Response(JSON.stringify(response), {
status: 200,
headers: {
'Access-Control-Allow-Origin':'*',
'Content-Type': 'application/json',
"Set-Cookie": seralized
},
});
const response = {
message: "Authenticated!",
};

const seralized = serialize(COOKIE_NAME, JSON.stringify(userData), {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "strict",
maxAge: MAX_AGE,
path: "/",
});

return new Response(JSON.stringify(response), {
status: 200,
headers: {
'Access-Control-Allow-Origin':'*',
'Content-Type': 'application/json',
"Set-Cookie": seralized
},
});
2 replies
TTCTheo's Typesafe Cult
Created by Revaycolizer on 9/20/2023 in #questions
Route handlers errors after updating
Guys anyone updated to version 13.5.2 and getting this error Expected "Response | Promise<Response>", got "Promise<NextResponse <any> | undefined>"
2 replies
TTCTheo's Typesafe Cult
Created by Revaycolizer on 9/8/2023 in #questions
Football live Stream Package
Which football live stream package should I use for nodejs and is it safe to use?
8 replies
TTCTheo's Typesafe Cult
Created by Revaycolizer on 9/5/2023 in #questions
Implementing Middleware
Hi guys been implementing Middleware to protect admin and user page but to some points I failed to protect two pages /adupload for admin to access and /home for only user to access. Below is the link to how I implemented it https://github.com/Revaycolizer/next-learn14/blob/main/middleware.ts
3 replies
TTCTheo's Typesafe Cult
Created by Revaycolizer on 9/5/2023 in #questions
Some of the conditions are omitted in middleware
some of conditions are not checked by the middleware as when a user is authenticated and navigates to /register he should be redirected back to /home but it does not do that only /login condition works but others do not work using codes below
import { verify } from 'jsonwebtoken';
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { COOKIE_NAME } from './app/constants/cookie';
import { cookies } from 'next/headers';

export async function middleware(req: NextRequest) {

const res = NextResponse.next()

const token = req.cookies.get(COOKIE_NAME);


if (!token) {
if (req.nextUrl.pathname.startsWith('/home')) {
const redirectUrl = req.nextUrl.clone()
redirectUrl.pathname = '/login'
redirectUrl.searchParams.set(`redirectedFrom`, req.nextUrl.pathname)
return NextResponse.redirect(redirectUrl)
}
else{
const redirectUrl = req.nextUrl.clone()
redirectUrl.pathname = '/'
redirectUrl.searchParams.set(`redirectedFrom`, req.nextUrl.pathname)
return NextResponse.redirect(redirectUrl)
}
}

const user = JSON.parse(token.value)

if (user.role === "USER") {
if (req.nextUrl.pathname.startsWith('/adupload')) {
return NextResponse.rewrite(new URL('/home', req.url))
}

if (req.nextUrl.pathname.startsWith('/login')) {
const redirectUrl = req.nextUrl.clone()
redirectUrl.pathname = '/home'
redirectUrl.searchParams.set(`redirectedFrom`, req.nextUrl.pathname)
return NextResponse.redirect(redirectUrl)
}

if (req.nextUrl.pathname.startsWith('/register')) {
const redirectUrl = req.nextUrl.clone()
redirectUrl.pathname = '/home'
redirectUrl.searchParams.set(`redirectedFrom`, req.nextUrl.pathname)
return NextResponse.redirect(redirectUrl)
}
}
return res
}

export const config = {
matcher: [
'/home/:path*',

],
}
import { verify } from 'jsonwebtoken';
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { COOKIE_NAME } from './app/constants/cookie';
import { cookies } from 'next/headers';

export async function middleware(req: NextRequest) {

const res = NextResponse.next()

const token = req.cookies.get(COOKIE_NAME);


if (!token) {
if (req.nextUrl.pathname.startsWith('/home')) {
const redirectUrl = req.nextUrl.clone()
redirectUrl.pathname = '/login'
redirectUrl.searchParams.set(`redirectedFrom`, req.nextUrl.pathname)
return NextResponse.redirect(redirectUrl)
}
else{
const redirectUrl = req.nextUrl.clone()
redirectUrl.pathname = '/'
redirectUrl.searchParams.set(`redirectedFrom`, req.nextUrl.pathname)
return NextResponse.redirect(redirectUrl)
}
}

const user = JSON.parse(token.value)

if (user.role === "USER") {
if (req.nextUrl.pathname.startsWith('/adupload')) {
return NextResponse.rewrite(new URL('/home', req.url))
}

if (req.nextUrl.pathname.startsWith('/login')) {
const redirectUrl = req.nextUrl.clone()
redirectUrl.pathname = '/home'
redirectUrl.searchParams.set(`redirectedFrom`, req.nextUrl.pathname)
return NextResponse.redirect(redirectUrl)
}

if (req.nextUrl.pathname.startsWith('/register')) {
const redirectUrl = req.nextUrl.clone()
redirectUrl.pathname = '/home'
redirectUrl.searchParams.set(`redirectedFrom`, req.nextUrl.pathname)
return NextResponse.redirect(redirectUrl)
}
}
return res
}

export const config = {
matcher: [
'/home/:path*',

],
}
6 replies
TTCTheo's Typesafe Cult
Created by Revaycolizer on 9/5/2023 in #questions
Fetching data in server Component
Is there a way I can fetch data from my api generated in my api routes in server Component rather than writing the route handling logic in my server Component
3 replies
TTCTheo's Typesafe Cult
Created by Revaycolizer on 9/4/2023 in #questions
Error:localhost redirected too many times
Whenever the user is authenticated and a web page is refreshed I keep getting this error "error:localhost redirected too many times try to clear cookies". Using codes below b
import { redirect } from 'next/navigation'
import { cookies } from 'next/headers'
import { verify,sign } from "jsonwebtoken";
import { COOKIE_NAME } from '../constants/cookie';
import prisma from "@/prisma/client";

export const revalidate = 0;

export default async function Protect({

children,
}: {
children: React.ReactNode
}){
const session = await getServerSession(authOptions)

// const user = await getUserAction()
// const cookieStore = cookies()
// const authorization = cookieStore.get('adminToken')
// console.log(authorization?.value)
// const user = JSON.parse(authorization!.value)

const cookieStore = cookies();

const token = cookieStore.get(COOKIE_NAME);

if (!token) {
redirect("/")
}

const { value } = token;

const secret = process.env.JWT_SECRET || "";

var decode = verify(value, secret) as { user: { id: string; email: string; name: string; image: string | null; role: string; hashedPassword: string }; iat: number; exp: number };
;

const useri = decode.user

const email = useri.email;


const user = await prisma.user.findFirst({
where:{
email:email,
ustate:"NON_BLOCKED"
},
select:{
id:true,
name:true,
role:true,
}

})

if (!user) {
redirect("/")
}

if(user.role == "USER"){
redirect("/home")
}

if(user.role == "ADMIN")
return(
<section>{children}</section>
)
}
import { redirect } from 'next/navigation'
import { cookies } from 'next/headers'
import { verify,sign } from "jsonwebtoken";
import { COOKIE_NAME } from '../constants/cookie';
import prisma from "@/prisma/client";

export const revalidate = 0;

export default async function Protect({

children,
}: {
children: React.ReactNode
}){
const session = await getServerSession(authOptions)

// const user = await getUserAction()
// const cookieStore = cookies()
// const authorization = cookieStore.get('adminToken')
// console.log(authorization?.value)
// const user = JSON.parse(authorization!.value)

const cookieStore = cookies();

const token = cookieStore.get(COOKIE_NAME);

if (!token) {
redirect("/")
}

const { value } = token;

const secret = process.env.JWT_SECRET || "";

var decode = verify(value, secret) as { user: { id: string; email: string; name: string; image: string | null; role: string; hashedPassword: string }; iat: number; exp: number };
;

const useri = decode.user

const email = useri.email;


const user = await prisma.user.findFirst({
where:{
email:email,
ustate:"NON_BLOCKED"
},
select:{
id:true,
name:true,
role:true,
}

})

if (!user) {
redirect("/")
}

if(user.role == "USER"){
redirect("/home")
}

if(user.role == "ADMIN")
return(
<section>{children}</section>
)
}
4 replies
TTCTheo's Typesafe Cult
Created by Revaycolizer on 9/2/2023 in #questions
Implementing get Request with Prisma
I impleented login route using prisma and also Redis is being used for session management but when a user is logged in another device and the other user opens the website in another device without logging in the returned user is the one who was authenticated from the other device, How can i fix this below is the source codes
import { NextResponse,type NextRequest } from "next/server";
import prisma from "@/prisma/client";
import {Redis} from "@upstash/redis"
import bcrypt from "bcrypt";

export const revalidate = 0;

const redis = Redis.fromEnv();

export async function POST(req: NextRequest, res: NextResponse) {
try {
const body = await req.json();
const { email, password } = body;

if (!email || !password) {
return new NextResponse("Email and password are required", { status: 400 });
}

const user = await prisma.user.findFirst({
where: {
email: email as string,
role: "USER",
ustate:"NON_BLOCKED",
}, select: {
id: true,
email: true,
name: true,
image: true,
role:true,
hashedPassword:true
},
});

if (!user || !user.hashedPassword) {
return new NextResponse("User not found", { status: 404 });
}

const passwordMatch = await bcrypt.compare(password, user.hashedPassword);

if (!passwordMatch) {
return new NextResponse("Invalid credentials", { status: 401 });
}

const member = await redis.set("user",user)
console.log(member)


const response = {
message: "Authenticated!",
};

return new Response(JSON.stringify(response), {
status: 200,
});


} catch (error) {
console.error("Error fetching user:", error);
return new NextResponse("Internal Error", { status: 500 });
}
}
import { NextResponse,type NextRequest } from "next/server";
import prisma from "@/prisma/client";
import {Redis} from "@upstash/redis"
import bcrypt from "bcrypt";

export const revalidate = 0;

const redis = Redis.fromEnv();

export async function POST(req: NextRequest, res: NextResponse) {
try {
const body = await req.json();
const { email, password } = body;

if (!email || !password) {
return new NextResponse("Email and password are required", { status: 400 });
}

const user = await prisma.user.findFirst({
where: {
email: email as string,
role: "USER",
ustate:"NON_BLOCKED",
}, select: {
id: true,
email: true,
name: true,
image: true,
role:true,
hashedPassword:true
},
});

if (!user || !user.hashedPassword) {
return new NextResponse("User not found", { status: 404 });
}

const passwordMatch = await bcrypt.compare(password, user.hashedPassword);

if (!passwordMatch) {
return new NextResponse("Invalid credentials", { status: 401 });
}

const member = await redis.set("user",user)
console.log(member)


const response = {
message: "Authenticated!",
};

return new Response(JSON.stringify(response), {
status: 200,
});


} catch (error) {
console.error("Error fetching user:", error);
return new NextResponse("Internal Error", { status: 500 });
}
}
3 replies
TTCTheo's Typesafe Cult
Created by Revaycolizer on 8/31/2023 in #questions
Implementing login with Prisma
Below is the source code of my api but I figure out that any one entering credentials when an entered email resemble that of the one in the database, the user is authenticated without checking the corresponding password, how can I fix this, as the stored password is hashed?
import { NextResponse,type NextRequest } from "next/server";
import prisma from "@/prisma/client";
import {Redis} from "@upstash/redis"


const redis = Redis.fromEnv();

export async function POST(req: NextRequest, res: NextResponse) {
try {
const body = await req.json();
const { email, password } = body;

console.time()

if (!email || !password) {
return new NextResponse("Email and password are required", { status: 400 });
}

const user = await prisma.user.findFirst({
where: {
email: email as string,
role: "ADMIN",
ustate:"NON_BLOCKED",
}, select: {
id: true,
email: true,
name: true,
image: true,
role:true
},
});

if (!user) {
return new NextResponse("User not found", { status: 404 });
}

const member = await redis.set("user",user)
console.log(member)

const response = {
message: "Authenticated!",
};

console.timeEnd()

return new Response(JSON.stringify(response), {
status: 200,
});


} catch (error) {
console.error("Error fetching user:", error);
return new NextResponse("Internal Error", { status: 500 });
}
}
import { NextResponse,type NextRequest } from "next/server";
import prisma from "@/prisma/client";
import {Redis} from "@upstash/redis"


const redis = Redis.fromEnv();

export async function POST(req: NextRequest, res: NextResponse) {
try {
const body = await req.json();
const { email, password } = body;

console.time()

if (!email || !password) {
return new NextResponse("Email and password are required", { status: 400 });
}

const user = await prisma.user.findFirst({
where: {
email: email as string,
role: "ADMIN",
ustate:"NON_BLOCKED",
}, select: {
id: true,
email: true,
name: true,
image: true,
role:true
},
});

if (!user) {
return new NextResponse("User not found", { status: 404 });
}

const member = await redis.set("user",user)
console.log(member)

const response = {
message: "Authenticated!",
};

console.timeEnd()

return new Response(JSON.stringify(response), {
status: 200,
});


} catch (error) {
console.error("Error fetching user:", error);
return new NextResponse("Internal Error", { status: 500 });
}
}
20 replies
TTCTheo's Typesafe Cult
Created by Revaycolizer on 8/30/2023 in #questions
Vercel Caching Data during Deployment
Anybody hosted a website in Vercel recently, as when a data is fetched during deployment, it caches it even if the data is changed, so everytime a data is changed I need to click redeploy again, how can I fix this? Tried
export const revalidate = 0;
export const revalidate = 0;
also tried
export const revalidate = false ;
export const revalidate = false ;
But nothing works
9 replies
TTCTheo's Typesafe Cult
Created by Revaycolizer on 8/23/2023 in #questions
Storing and retrieving cookie
Anyone successfully stored cookie in one route handler and retrieving it in another route handler?
23 replies
TTCTheo's Typesafe Cult
Created by Revaycolizer on 8/21/2023 in #questions
Storing and getting cookie in api
Anyone successfully created a login api and stored cookies using prisma and then created an API to fetch the cookie?
2 replies
TTCTheo's Typesafe Cult
Created by Revaycolizer on 8/19/2023 in #questions
Fetching data from API endpoints
Is there a way to fetch data from client Component without exposing API endpoints on frontend?
9 replies
RRefine
Created by ratty-blush on 7/22/2023 in #ask-any-question
Route protection
Anyone ever used route protection using refine and Zustand for state management
4 replies
TTCTheo's Typesafe Cult
Created by Revaycolizer on 7/12/2023 in #questions
Handling cors using axios
How can I perform XMLHttpRequest using axios
4 replies
TTCTheo's Typesafe Cult
Created by Revaycolizer on 6/10/2023 in #questions
Implementing route protection
I tried implementing route protection in nextjs 13.4.4 but did not work as a user signs in but is not redirected to the protected pages , below is the codes privateroute.tsx
import { Spinner } from "@chakra-ui/react";
import { redirect, usePathname } from "next/navigation";


import { useUser } from "./middleware";


// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const WithPrivateRoute = (Component: React.FunctionComponent<any>) => {
const NewComponent = () => {
const { user, isLoading } = useUser();

// if (isLoading) return <Spinner />;
if (!user) redirect("/");

return <Component />;
};

return NewComponent;
};
import { Spinner } from "@chakra-ui/react";
import { redirect, usePathname } from "next/navigation";


import { useUser } from "./middleware";


// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const WithPrivateRoute = (Component: React.FunctionComponent<any>) => {
const NewComponent = () => {
const { user, isLoading } = useUser();

// if (isLoading) return <Spinner />;
if (!user) redirect("/");

return <Component />;
};

return NewComponent;
};
3 replies
TTCTheo's Typesafe Cult
Created by Revaycolizer on 5/28/2023 in #questions
Update password for non authenticated user
How can I change password for a non authenticated user??
3 replies