Skip to content

Execute server-only code inside site.ts #99

Answered by ElMassimo
marcopixel asked this question in Q&A
Discussion options

You must be logged in to vote

Hi @marcopixel!

You can run server-only code behind a import.meta.env.SSR guard. For example:

let commitHash

if (import.meta.env.SSR) {
  const { execSync } = require('child_process')
  commitHash = execSync('git rev-parse --short HEAD').toString().trim()
}

However, if you want a more "universal" approach, I would recommend using an env var with define, for example in iles.config.ts where you can use node directly:

export default defineConfig({
  vite: {
    define: {
      'import.meta.env.APP_GIT_SHA': JSON.stringify(commitHash),
    },
  },
})

Just in case, here's a related example, but setting git timestamps to the frontmatter of each page.

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@marcopixel
Comment options

Answer selected by ElMassimo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants