Next.js Discord

Discord Forum

How can I get the path of file in App router?

Unanswered
Turkish Angora posted this in #help-forum
Open in Discord
Turkish AngoraOP
I want to run revalidatePath and redirect in server action. All of my actions use the same path (the folder that the action is placed in).

/app/(models)/items/actions.ts:
// get the current file path on the server
const currentFile = __filename
// /Users/varna/turborepo/.next/server/app/(models)/items/page.js

// get the string after ".next/server/app"
let path = currentFile.split(".next/server/app")[1]
  
// remove everything after the last "/"
path = path.substring(0, path.lastIndexOf("/"))

export const removeItem = action(idSchema, async (id) => {
  await items.delete({
    where: { id }
  })

  revalidatePath(path)
  redirect(path)
})

If I enable --turbo, then that path changes to /Users/varna/turborepo/.next/server/chunks/[root of the server]__34492f._.js. Is there a better way to get the folder name where action exists?

2 Replies

Turkish AngoraOP
For now, I'm using this:
/lib/dirnameToPathname.ts:
// takes `__dirname`
export function dirnameToPathname(dirname: string): string {
  let path = dirname.split(" ")[0]
  path = path.split("/app")[1]
  path = path
    .split("/")
    .filter((part) => !part.includes("("))
    .filter((part) => !part.includes("."))
    .join("/")
  return path
}

and in /actions.ts
const path = dirnameToPathname(__dirname)
or maybe I should just use
const path = dirnameToPathname(import.meta.url)