Next.js Discord

Discord Forum

Redirect user if pathname is empty based on an XHR call

Unanswered
Brown bear posted this in #help-forum
Open in Discord
Avatar
Brown bearOP
I'm using appDir and when the user navigates to a new page I want to check if the path name is '/' and if it is redirect them to one of our default 'boards'. The catch is that to get the default board I have to make an XHR call. I'm also using SWR. I've tried doing it like this butdefaultBoardRoute comes out as undefined so it redirects to /board/undefined/route/undefined - can anyone point out where I'm going wrong?

I'm doing this in a component some way down the page loading hierarchy, if you think there's a better place for this (I tried in layout.tsx but it would have required me to make it a client side component to make it work which didn't seem right):

export default function Board() {

    const pathname = usePathname()

    const {
        data: defaultBoardRoute,
        error
    } = useSWR<BoardRouteInfoDto>(api('/boardRoutes/default'), fetcher)

    if (!pathname || pathname === '/') {
        redirect(`/board/${defaultBoardRoute?.boardId}/route/${defaultBoardRoute?.routeId}`)
    }
... rest of page

1 Reply

Avatar
Brown bearOP
I answered my own question with Dynamic Routes https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes

This let me define folders with [] wrapped around the name to represent the variables

So I made:

board
| -- [boardId]
| ---- route
| ------ [routeId]
| -------- page.tsx

and that looked like:

type BoardRouteParams = {
    boardId: string,
    routeId: string
}

export default function BoardRoute({ params }: {params: BoardRouteParams} ) {
  return (
    <main>
            Hi thar! Board = {params.boardId}, Route = {params.routeId}
        </Auth>
    </main>
  )
}