Skip to content

docs: describe how to create server-side only services #53168

Closed

Description

@alexcibotari

Which @angular/* package(s) are relevant/related to the feature request?

platform-browser, platform-server

Description

As a developer, I would need a service to be injected and executed only on the server side as it contains a connection Token in the request URL.

Proposed solution

To define Injectable parameters you can define a platform where you would like a service to be injectable: server or browser

Alternatives considered

For the moment I'm using StateTransfer, to provide data, but still the service with a secure token is present the browser bundle, where I have a token exposed

Activity

  1. added
    area: server
    on Nov 27, 2023
  2. added this to the needsTriage milestone on Nov 27, 2023
  3. alan-agius4 commented on Nov 27, 2023

    @alan-agius4
    Contributor

    This is currently already possible by using DI and providing a different provider based on the platform.

    data-service.service.ts

    import { Injectable } from '@angular/core';
    
    @Injectable()
    export abstract class DataServiceService {
      abstract get(id: string): string
    }
    
    export class DataServiceServiceServer extends DataServiceService {
       get(id: string): string {
        return 'server-data-performed-with-secret-tokens';
       }
    }
    
    export class DataServiceServiceBrowser extends DataServiceService {
      get(id: string): string {
       return 'browser-data';
      }
    }

    app.config.server.ts

    const serverConfig: ApplicationConfig = {
      providers: [
        provideServerRendering(),
        {
          provide: DataServiceService,
          useClass: DataServiceServiceServer
        }
      ]
    };

    app.config.ts

    export const appConfig: ApplicationConfig = {
      providers: [
        provideRouter(routes),
        provideClientHydration(),
        {
          provide: DataServiceService,
          useClass: DataServiceServiceBrowser,
        },
      ],
    };
  4. added
    area: docs
    on Nov 28, 2023
  5. AndrewKushnir commented on Nov 28, 2023

    @AndrewKushnir
    Contributor

    It looks like this might be a good addition to the docs, I'm updating ticket title to reflect that.

  6. changed the title [-]Server side only service[/-] [+]docs: describe how to create server-side only services[/+] on Nov 28, 2023
  7. added
    P4
    on Nov 28, 2023
  8. modified the milestones: needsTriage, Backlog on Nov 28, 2023
  9. added
    P3
    and removed
    P4
    on Nov 28, 2023
  10. jdgamble555 commented on Feb 28, 2024

    @jdgamble555

    This doesn't transfer the state. Should we use transferState on this? How would we get the server data hydrated without replacing it with the browser version?

    J

  11. jdgamble555 commented on Feb 29, 2024

    @jdgamble555

    I tried to use DI, but the useState cannot be ran before the bootstrap:

    https://github.com/jdgamble555/angular-state-test

    We need a way to transfer the state.

    J

  12. jdgamble555 commented on Mar 3, 2024

    @jdgamble555

    Got it working with APP_INITIALIZER.

    https://dev.to/jdgamble555/preloading-data-in-angular-universal-20lj

    J

    This really should be some kind of pre-made provider.

  13. jdgamble555 commented on Mar 14, 2024

    @jdgamble555

    @alan-agius4 - I keep coming back to this. I don't want to load the same service on every route, some routes may have a specific service.

    How would you do this per route?

    If I use this method on the server, it will not get populated.

    const serverConfig: ApplicationConfig = {
      providers: [
        provideServerRendering(),
        provideRouter(
          [
            {
              path: '',
              component: SomeComponent,
              resolve: { data: SomeResolver },
              providers: [
                {
                  provide: DataServiceService,
                  useClass: DataServiceServiceServer
                }
             ]
            }
          ]
        )
      ]
    };
    
    export const config = mergeApplicationConfig(serverConfig, appConfig);

    I would think I would use the resolver to call a server service, then use the abstract for the browser version, but this will not work as the useClass never gets triggered.

    This should be updated in the docs with a way to do this for the whole app AND some way to do this per route.

    J

  14. imaksp commented on Mar 19, 2024

    @imaksp
    Contributor

    Hi @jdgamble555 I agree that there should be some proper way to do this at route level, but I think if you just call server only service in ngOnInit by checking isPlatformServer & save return data in transfer state then it should be readily available on client side & angular should also automatically cache this service response on server.

    & I still think there should be some more explicit way of setting transfer state at route level.

  15. jdgamble555 commented on Mar 19, 2024

    @jdgamble555

    Hi @imaksp. I appreciate your input but there are several problems here.

    1. Async input should be done in the resolver before the component is loaded. ngOninit will not wait for async by default, even when you put async in front of it
    2. I'm not calling an endpoint, I want to load data directly from the server on the first load, not call another endpoint.
    3. If I use isPlatformServer, it will add my server-only data to the client application. Not only is this a security problem, it is adding extra overhead to my client bundle I don't need.

    But this post is about the docs with loading in the resolver (or provider) before the component is loaded ONLY from the server and available on the server and browser version. Having transferState load anything from the resolver should also be done automatically, but that is another issue.

    J

  16. imaksp commented on Mar 19, 2024

    @imaksp
    Contributor

    Yes if you are not using endpoint then some code might get exposed but if its api server code won't be exposed & server only secret from env variable could be used for api.

    I think here function like next's getServerSideProps or getStaticProps would be more appropriate. Something like server only resolve function for route.

  17. imaksp commented on Dec 19, 2024

    @imaksp
    Contributor
    1. If I use isPlatformServer, it will add my server-only data to the client application. Not only is this a security problem, it is adding extra overhead to my client bundle I don't need.

    J

    Hi @jdgamble555 , I believe if you return data from server only service & call it from component's constructor by checking isPlatformServer then that code won't be included in client bundle & secrets used in server service won't be exposed. & you can get that data on client using transferState.get after checking isPlatformBrowser.

  18. jdgamble555 commented on Jan 15, 2025

    @jdgamble555

    @imaksp - This is incorrect.

    Using isPlatformServer will prevent server code from running in the browser, but it still gets put into the JS.

    However, this may be soon possible with something similar to "server-only" components.

    analogjs/analog#989

    I have not tested any of this.

    J

  19. angular-automatic-lock-bot commented on Jan 16, 2026

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  20. locked and limited conversation to collaborators on Jan 16, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3area: docsarea: server

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions