i need to make return button which will return to previous page.
First i tried to make component:
"use client";
import React from "react";
import {useRouter} from "@i18n/routing";
import {IRedirect} from "@t/hooks/redirect";
const RedirectBack = ({children, redirectTo, className}: IRedirect) => {
const router = useRouter();
const redirect = () => {
switch (redirectTo) {
case "back":
router.back();
default:
return;
}
};
return (
<div
className={className}
onClick={redirect}>
{children}
</div>
);
};
export default RedirectBack;
but it will cause it to be "use client"
and i want to avoid it, so i found the way, where i can create route handler
and create a GET
request which will redirect to another page
import {redirect, useRouter} from "@i18n/routing";
import {IRedirectHandler} from "@t/route-handlers/redirect";
import {NextResponse} from "next/server";
export async function GET(_request: Request, context: {params: IRedirectHandler}) {
redirect(`/${context.params.to}`);
}
but the only way I know how to return to the previous page is to use useRouter
with route.back()
command, but if i try to do so inside route handler
and GET
request i get an error with code 500
HTTP/1.1 500 Internal Server Error
link: <http://localhost:3000/en/api/route-handlers/redirect/back>; rel="alternate"; hreflang="en", <http://localhost:3000/ua/api/route-handlers/redirect/back>; rel="alternate"; hreflang="ua"
x-middleware-rewrite: /en/api/route-handlers/redirect/back
vary: RSC, Next-Router-State-Tree, Next-Router-Prefetch
Date: Sat, 12 Oct 2024 18:01:55 GMT
Connection: keep-alive
Keep-Alive: timeout=5
Transfer-Encoding: chunked
GET /en/api/route-handlers/redirect/back HTTP/1.1
Host: localhost:3000
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:132.0) Gecko/20100101 Firefox/132.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: uk,en-US;q=0.7,en;q=0.3
Accept-Encoding: gzip, deflate, br, zstd
Connection: keep-alive
Cookie: NEXT_LOCALE=en
Upgrade-Insecure-Requests: 1
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: cross-site
Priority: u=0, i
so is there any way to use useRoute
inside route handler
OR
Still use route handler
but be able to return to previous page?
i did try but it cause error request code 500
and do nothing
import {redirect, useRouter} from "@i18n/routing";
import {IRedirectHandler} from "@t/route-handlers/redirect";
import {NextResponse} from "next/server";
export async function GET(_request: Request, context: {params: IRedirectHandler}) {
const router = useRouter();
router.back();
}
I’m hoping to find some way to get back to the previous page using route handler