.server.js / .client.js / .shared.js

Adding .server.js / .client.js / .shared.js to a file has following effect:

  • For all files, it asserts in which environment the file is loaded.
  • For + files, it changes in which environment the file is loaded.

For all files

.server.js

The most common use case for .server.js is to ensure that a file that contains secret information is never accidentally leaked to the client-side (and thus made public).

// /server/database/credentials.server.js
 
// Should *never* be imported by client-side code. We use .server.js to guarantee that.
export default {
  password: 'WLa!9HW?E10a'
}

It's crucial that credentials.server.js is never loaded by the client-side: otherwise, because the client-side JavaScript is public, everyone could read the password defined in credentials.server.js.

If some client-side code does load credentials.server.js then Vike will throw an error and abort any attempt to build for production. (In development Vike shows a warning.)

[vike][Wrong Usage] Server-only module /server/database/credentials.server.js (https://vike.dev/file-env) imported on the client-side by /pages/product/@id/+Page.js

.client.js

You can use .client.js to ensure that a file always runs on the client-side.

// /utils/someClientCode.client.js
 
// This code only works in the browser; we use .client.js to assert that this file is
// never loaded on the server-side.
 
window.onclick = () => {
  // ...
}

.shared.js

The file extension .shared.js has an effect only for + files (see section below): it's useless for other files.

For + files

For + files, the most common use case is to change the environment of the data() hook: by renaming +data.js to +data.shared.js / +data.server.js / +data.client.js you tell Vike in which environment the data() hook should be loaded and executed, see API > data() hook > Client-side.

Essentially, it's a simpler way to set the meta.env setting of a + file. Adding .server.js / .client.js / .shared to a + file, for example /pages/product/@id/+data.js, is equivalent to:

// /pages/product/@id/+config.ts
 
export default {
  meta: {
    data: {
      // .shared.js
      env: { server: true, client: true },
      // .server.js
      env: { server: true, client: false },
      // .client.js
      env: { server: false, client: true }
    }
  }
}