src > app > api > users > logout > route.ts
import { NextResponse } from "next/server";
export async function GET(){
try {
const response = NextResponse.json({
message: 'Logout successfull',
success: true
});
response.cookies.set('token', '', {
httpOnly: true,
expires: new Date(0)
});
return response;
} catch (error: any) {
return NextResponse.json({error: error.message}, {status: 400});
}
}
-----------------------------------------------------
src > app > profile > page.tsx
"use client"
import axios from "axios"
import { useRouter } from "next/navigation"
export default function profilePage(){
const router = useRouter();
const logout = async () =>{
try {
await axios.get('/api/users/logout');
router.push('/login');
} catch (error) {
console.log(error);
}
}
return(
<div>
<h1 className="page-hd">Profile page</h1>
<button onClick={logout}>Logout</button>
</div>
)
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter